5

I'm following a tutorial on how to create a Windows Service that will send automated emails on my web server. I've got the tutorial working, however, the example code executes the service every 60mins, instead, I'd like the service executed once a day, every 24 hours, say at 9am every morning.

Below is the sample code

    private Timer scheduleTimer = null;
    private DateTime lastRun;
    private bool flag;

    public StarEmailService()
    {
        InitializeComponent();
        if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
        {
            System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailLog");
        }
        eventLogEmail.Source = "EmailSource";
        eventLogEmail.Log = "EmailLog";

        scheduleTimer = new Timer();
        scheduleTimer.Interval = 1 * 5 * 60 * 1000;
        scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);

    }

    protected override void OnStart(string[] args)
    {
        flag = true;
        lastRun = DateTime.Now;
        scheduleTimer.Start();
        eventLogEmail.WriteEntry("Started");
    }

    protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (flag == true)
        {
            ServiceEmailMethod();
            lastRun = DateTime.Now;
            flag = false;
        }
        else if (flag == false)
        {
            if (lastRun.Date < DateTime.Now.Date)
            {
                ServiceEmailMethod();
            }
        }
    }

The line scheduleTimer.Interval = 1 * 5 * 60 * 1000; appears to be the code which sets the interval to 60mins, however, am unsure what would I need to amend this to in order to make it run every 24 hours at 9am?

Any advice would be appreciated.

Thanks.

1
  • 1
    If you care about wall time, a timer is the wrong tool for the job. You want a scheduler. And, if the only purpose of your service is to wait until the scheduled time and then run useful code, it would be better to create a scheduled task and not have your code (pointlessly) running all the rest of the time. Jun 1, 2015 at 10:36

2 Answers 2

10

You have couple of options:

Don't rely on other timers as they will get out of sync in (near) future.

4

It is probably better to set your timer to smaller interval, and check the system time similar to your code does now. This code should send an email once a day on or after 9 am. The smaller your timer interval, the more accurate it will be to 9 am. For example, if you keep the timer interval at 60 minutes, the service will check the system time once an hour and the email will be sent between 9am and 10am. If you set the timer to 10 minutes, the service will check the system time once every tem minutes and send the email between 9:00 and 9:10am.

This method does not go out of sync over time, because it uses the system clock, not the timer interval to know when to fire.

Remove lastRun DateTime field and all references to it. Remove flag field and references. Add a DateTime field called nextRun:

private DateTime nextRun = DateTime.MinValue;

Add a function GetNextRun:

private static DateTime GetNextRun(DateTime lastRun)
{
    var next = lastRun.AddDays(1);
    return new DateTime(next.Year, next.Month, next.Day, 9, 0, 0); 
}

Change ScheduleTimer Elapsed to:

protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (DateTime.Now < nextRun) return;

    nextRun = GetNextRun(DateTime.Now);
    ServiceEmailMethod();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.