Reputation: 2642
I found this answer and I try to do follow that, but It didn't bring me any work while I start my service. One thing that I couldn't understand is :`_timer = new Timer(10 * 60 * 1000); // every 10 minutes
I want to perform my service daily at 10:00PM, how could I do that?
Upvotes: 5
Views: 13166
Reputation: 1058
Windows has a built in task scheduler that is much better to use for any scheduling needs. There are a lot of things that can go wrong when working with scheduling tasks such as a system reboot, day light savings.
Can refer to a blog by Ayende about some of the issues wrong with making your own scheduler. Rotten scheduling: Don’t roll your own
Upvotes: 3
Reputation: 148170
You can find out the difference
between current time
and your desired schedule time
and make the elapse interval accordingly. This way the event of timer will fire once
at the sheduled time. Set the interval of time to 24 hours when it is elapsed.
private System.Timers.Timer _timer;
private void SetTimer()
{
DateTime currentTime = DateTime.Now;
int intervalToElapse = 0;
DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 10,0,0);
if (currentTime <= scheduleTime)
intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
else
intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
_timer = new System.Timers.Timer(intervalToElapse);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//do your work
_timer.Interval = (24 * 60 * 60 * 1000);
}
Upvotes: 8
Reputation: 2882
Instead of rolling your own timer you can use Quartz.NET to host the service. It works well and has some additional features like catch up (if you need it) as well as the ability to farm the service.
http://quartznet.sourceforge.net/
Upvotes: 4
Reputation: 65702
Even though the Timer is polling every ten minutes in the answer you reference - its only processing once a day:
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// ignore the time, just compare the date
if (_lastRun.Date < DateTime.Now.Date)
{
To make it happen at 10:00AM add another condition, eg:
_lastRun.Date < DateTime.Now.Date && DateTime.Now.Hour = 10
The ten minutes is the time used as a polling frequency.
Upvotes: 1