I wanted to start a Windows service to run a function everyday at specific time.
What method i should consider to implement this? Timer or using threads?
I wanted to start a Windows service to run a function everyday at specific time.
What method i should consider to implement this? Timer or using threads?
if it is one in a day, why you don't use task scheduler? windows service is useful when you want run task many time in minute. so if you want to run a program in a specific time, its better to use task scheduler and set event of task scheduler on a specific time in day. I do many thing with task scheduler and its perfect. you can set rout of program in task scheduler and set interval time to run it. if you want to run a program every 5 min in a day still you can use task scheduler and its better way.
Good answer (I used your code), but one problem with this line:
If DateTime.now is later than scheduleTime, you will go negative and this will generate an exception when assigning to timer.Interval.
I used:
Then do the subtraction.
Are you sure, you need a service, that runs only one time per day?
Maybe Windows Task Schedule will be better solution?
(1) On first start, Set _timer.Interval to the amount of milliseconds between the service start and schedule time. This sample set schedule time to 7:00 a.m. as _scheduleTime = DateTime.Today.AddDays(1).AddHours(7);
(2) On Timer_Elapsed, reset _timer.Interval to 24 hours (in milliseconds) if current interval is not 24 hours.
Edit:
Sometimes people want to schedule the service to start at day 0, not tomorrow so they change
DateTime.Today.AddDays(0)
.If they do that and set a time in the past it causes an error setting the Interval with a negative number.Use Windows built in Task Scheduler (http://windows.microsoft.com/en-us/windows7/schedule-a-task) or Quartz.net.
Unless ... you have a service that's doing lots of other processing and needs to be running all the time in which case a Timer might be appropriate.