Search code examples
c#windowsservicebackgroundscheduling

Schedule Windows Service to run at 3:00am each day


protected override void OnStart(string[] args)
{
    aTimer = new Timer();
    var timer = System.Configuration.ConfigurationManager.AppSettings["Timer"].ToString(); //Appconfig "03:00"
    var date = DateTime.Now;

    DateTime scheduled = DateTime.ParseExact(timer, "HH:mm",
                                            CultureInfo.InvariantCulture);

    if (date > scheduled) scheduled = scheduled.AddDays(1);

    var test = scheduled.Subtract(date).TotalMinutes;

    aTimer.Interval = test;

    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Enabled = true;
    aTimer.AutoReset = false;

}

This code above run for the first time when start, and then it never run again even when the interval is set to run at 3:00am each day.

Update: Works great. I was wondering if there's a chance that it may overlap each event if I set the timer to run every 1 second. Does it wait for the event to end before starting a new one?


Solution

  • AutoReset should be true in order to raise the event multiple times. Why did you set it to false?

    See https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.autoreset?view=net-5

    But better is to use windows scheduler. Your code won't help in case of a reboot or restarted/stopped service.