Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule a C# Windows Service to perform a task daily

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?

like image 684
Nothing Avatar asked Aug 12 '12 00:08

Nothing


1 Answers

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);
}
like image 53
Adil Avatar answered Sep 30 '22 13:09

Adil