0

I have a windows service and I would like to insert a timer. How can I check if the present time is 9:00 AM ? I would like my service to check this every day. Thank you a lot

My try:

Datetime dt=Datetime.parse("09:00:00 everyday");
if(datetime.now -dt ==0)
{
   //fire event
}

Thats kinda sily of me though.

  • possible duplicate of [How might I schedule a C# Windows Service to perform a task daily?](http://stackoverflow.com/questions/503564/how-might-i-schedule-a-c-sharp-windows-service-to-perform-a-task-daily) – CodeCaster Jul 08 '12 at 07:59
  • 1
    This is very tricky! Windows is not a real-time system so this code might never run at 9 am. If you want something to happen at 9 am, use the windows scheduler. – Emond Jul 08 '12 at 08:10

4 Answers4

0

You need to make a timer and sets its interval to the timespan between now and tomorrow 9:00 AM. Next time the timer tick, set the interval again in the same way. You should use this Timer class: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
0

Please use DateTime.UtcNow.Hour to check current hour

By using UtcNow you will gets a DateTime object that is set to the current date and time on the computer, expressed as the Coordinated Universal Time (UTC).

HatSoft
  • 11,077
  • 3
  • 28
  • 43
0
var now = DateTime.Now;
var today = now.Date;
var nineAm = today.AddHours(9);

TimeSpan ts = nineAm - now;

var timeInMillisecondsTill9Am = ts.Milliseconds;

If(timeInMillisecondsTill9Am==0)
{
 //your code goes here
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
PraveenVenu
  • 8,217
  • 4
  • 30
  • 39
0

Since you don't know when someone may shutdown or reboot your computer or service then you need to make sure that you use a method robust enough to handle these kinds of interruptions.

I suggest that when your service checks every 5 minutes or so if the time is after 9am and if the last run date is yesterday. If so, you update the last run date to day (perhaps in a simple text file) and then run the "9:00am" task. In this way your task only runs once per day, fairly close to 9am, and is robust against reboots.

You'll need to use a standard .NET timer to trigger the checks - and if you're clever enough you can make it fire a few seconds after 9am.

Let me know if that's a good solution.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172