Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do timers in a windows service behave when the system is asleep?

Assuming I have a windows service which has a timer that is set to run every 6 hours, I would expect it to fire 4 times a day. Let's say : 0000, 0600, 1200 1800. (Military time, same as 00:00, etc...)

If the system goes to sleep at 1000, and wakes at 1700, what happens?

  1. will it fire again at 1900, because it has 2 hours on the timer?
  2. will it fire straight away (because it missed it's 1200 appointment), and then fire again at 2300 (adding it's 6 hours to the current time?)

I've noticed that when the computer goes to sleep, it doesn't fire the OnPause or OnContinue methods.

If anyone can shed some light on the behaviour of the system in the above cases, It'll be great know.
Cheers, and thanks in advance.

like image 512
Noctis Avatar asked Aug 25 '14 09:08

Noctis


People also ask

Do Windows services run in sleep mode?

When computer is under sleep mode, all programs get suspended. Hence, your program live stock will not be running.

What is System sleep timer?

What is a sleep timer? A sleep timer is a function that dictates how long your computer will sit idle before going into power-saving mode.

Why doesn t Windows go to sleep?

To make sure sleep mode is enabled, follow these steps: Step 1: Press WIN + I on your keyboard to launch Settings. Step 2: Select System from the menu tiles. Step 3: Make sure you're in the Power and Sleep tab.


1 Answers

As has already been mentioned in the comments: Use the task scheduler instead of timers. See this article for further discussion.

The question of how timers behave during sleep is still interesting, though. In the specific case you mention, option 2. will be the observed behavior. The timer will fire on resume because it missed an event during sleep and subsequently start counting from 0 again The next time it fires will thus be at 23:00. This answer has sample code to support the observation.

In case you want to detect when the system sleeps and resumes, subscribe to the SystemEvents.PowerModeChanged event. This event's PowerModeChangedEventArgs contains a Mode, of which you are interested in Suspend and Resume.

like image 148
Henrik H Avatar answered Oct 26 '22 23:10

Henrik H