0

I am a newbie to dotnet, and I have a C# code in a Windows Service application which have to run for every 24hours. For specifying the interval I used the below code:

var t=new System.Threading.Timer(e=>method(),null,Timespan.Zero,TimeSpan.FromHours(24));

So the above line of code would check for the condition for every 24 hours. My doubt is, what happens to the process in the mean time(like between 24 hours). Does it goes to sleep on its own? if so, is there any way to know if the process is at sleep

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Naruhina
  • 53
  • 4
  • The lifetime of the process is defined externally to the call, you'd need to ensure the process stayed alive for the timer event to fire. – Jodrell Sep 05 '22 at 06:30
  • If you want to learn how `System.Threading.Timer` works, you could look at the [source code](https://referencesource.microsoft.com/#mscorlib/system/threading/timer.cs,051a39d380760b26). – Andy Sep 05 '22 at 06:31
  • 3
    For such long time periods, it's almost always better to use e.g. windows scheduled tasks to *just run the program when it has work to do*. – Damien_The_Unbeliever Sep 05 '22 at 06:32
  • This seems pertinent, https://stackoverflow.com/q/64517214 – Jodrell Sep 05 '22 at 06:34
  • @Damien_The_Unbeliever, a good idea, while your OS is Windows but, similar mechanisms exist in other environments. – Jodrell Sep 05 '22 at 06:37
  • ... and also don't forget that this is running every 24h meaning: if you restart your service in between it is directly restarting and doing work so running in less than 24 h potentially. So if you want to have a "do-it-every-day-at-midnight"-job do it with a scheduled windows task or linux cron job. – Martin Sep 05 '22 at 06:38
  • 1
    @TheodorZoulias ,its a windows service application – Naruhina Sep 05 '22 at 09:50
  • Related: [What happens to timer in standby mode?](https://stackoverflow.com/questions/14821745/what-happens-to-timer-in-standby-mode) – Theodor Zoulias Sep 05 '22 at 10:11

1 Answers1

0

Does it goes to sleep on its own?

No, the current thread will continue to run, and do whatever you tell it to do. If you want the thread to sleep you need to tell it to sleep. And this is possibly what you should do for a console program, or trap it in a "press any key to continue" question.

If your application is an UI application there will be a main thread that listens for windows messages, in that case you should rarely if ever use Thread.Sleep on the UI thread.

The timer uses the OS to do the actual waiting, and this will eventually use some kind of hardware to raise timing events. When the timer elapses it will raise the event on the threadpool, so it may run concurrently with the thread that started the timer. Note that there are other timers that work slightly differently.

JonasH
  • 28,608
  • 2
  • 10
  • 23