14

I'm using Timer from Timers namespace. What happens to timer when PC goes to sleep or hibernates?

I have timer set to 6 hours delay.

What will happen in those situations.

1) Timer starts at hour 0 and goes to sleep/hibernation immediately. Then PC wakes at hour 5. Will my timer fire after next 1 hour or after next 6 hours?

2) Timer starts at hour 0 and goes to sleep/hibernation immediately. Then PC wakes at hour 7. Will my timer fire as soon as PC wakes or will it "miss" that one time and fire in next 5 hours? Will it start counting till next event from time of PC waking or from previous "missed" event?

Hooch
  • 28,817
  • 29
  • 102
  • 161
  • This is something you can easily test for yourself. Try it and post an answer. – Hans Passant Feb 11 '13 at 22:07
  • What were the the results when you tried with ,say, 5 mins. Or you haven't tried yet? – I4V Feb 11 '13 at 22:08
  • @HansPassant I told at the begging of my question that I'm not able to test it now. – Hooch Feb 11 '13 at 22:08
  • Possibly duplicate of http://stackoverflow.com/questions/8229916/how-system-timers-timer-behave-in-wpf-application-after-hibernate-and-sleep – robert4 Jul 01 '16 at 05:09
  • This is a valid question - especially as reference information. I don't see a reason why it should be closed. IMHO we should rather reopen it. This would also potentially allow more concise answers. – oberlies May 04 '20 at 07:06

1 Answers1

28

Ok. I asked my friend and this are his results:

23:21:32 : Timer started
23:21:35 : PC Goes Sleep
23:22:50 : PC Wakes
23:22:50 : Timer fired
23:23:50 : Timer fired

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Test
{
    class Program
    {
        static System.Timers.Timer timer;

        static void Main(string[] args)
        {
            timer = new System.Timers.Timer();
            timer.Interval = 60 * 1000;
            timer.AutoReset = true;
            timer.Elapsed += timer_Elapsed;
            timer.Enabled = true;

            Console.WriteLine(String.Format("{0}:{1}:{2} : Timer started", DateTime.Now.ToLocalTime().Hour, DateTime.Now.ToLocalTime().Minute, DateTime.Now.ToLocalTime().Second));

            timer.Start();

            Thread.Sleep(Timeout.Infinite);
        }

        static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine(String.Format("{0}:{1}:{2} : Timer fired", DateTime.Now.ToLocalTime().Hour, DateTime.Now.ToLocalTime().Minute, DateTime.Now.ToLocalTime().Second));
        }
    }
}

So in short. After sleeping and waking timer checks if it has missed any event. If it missed one it will fire start counting till next event from 0.

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
Hooch
  • 28,817
  • 29
  • 102
  • 161