Run code at a certain time

74 views Asked by At

I'm using a C# Windows Service application where I'm having a object containing a stored procedure.

public class Sp
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int IntervalMin { get; set; }
    public DateTime LastRun { get; set; }
}

Right now I'm using this method to check if it's time to run:

public bool TimeToRun()
{
    return ((IntervalMin * 60) <= (DateTime.Now - LastRun).TotalSeconds);
}

The problem I have is that when the service is down during weekends and wakes up on monday TimeToRun will be true for all (considering IntervalMin isn't really high).

For example, there is one Sp with IntervalMin = 1440 (should be runned once a day), and lets says LastRun is Friday 14:00, on monday when service wakes up at 03:00 it will run, but I want it to be as close as possible to 14:00.

You have any tips of how I can build this kind of schedule? Do I need to use more properties that I set? It's no problem if it's like +/- 5 minutes or even more. TimeToRun() is checked about every each second.

LastRun is currently set to Datetime.Now, but I would like to use AddMinutes to cause no extra delays.

LastRun = LastRun.AddMinutes(IntervalMin)
0

There are 0 answers