Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Worker Check For When It's Midnight?

I want to create a background worker for a WinForm that triggers code whenever midnight rolls by.

I have an idea of how to do it, but I'm pretty sure it's not the best way to do it.

while(1==1)
{
//if Datetime.Now == midnight, execute code
//sleep(1second)
}
like image 452
sooprise Avatar asked Jun 16 '10 13:06

sooprise


2 Answers

Use a System.Timers.Timer and at application start up just calculate the difference between DateTime.Now and DateTime.Today.AddDays(0). Then set the interval for that amount.

I actually did something just like this recently:

public static class DayChangedNotifier
{
    private static Timer timer;

    static DayChangedNotifier()
    {
        timer = new Timer(GetSleepTime());
        timer.Elapsed += (o, e) =>
            {
                OnDayChanged(DateTime.Now.DayOfWeek);
                timer.Interval = this.GetSleepTime();
            };
        timer.Start();

        SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
    }

    private static void SystemEvents_TimeChanged(object sender, EventArgs e)
    {
        timer.Interval = GetSleepTime();
    }

    private static double GetSleepTime()
    {
        var midnightTonight = DateTime.Today.AddDays(1);
        var differenceInMilliseconds = (midnightTonight - DateTime.Now).TotalMilliseconds;
        return differenceInMilliseconds;
    }

    private static void OnDayChanged(DayOfWeek day)
    {
        var handler = DayChanged;
        if (handler != null)
        {
            handler(null, new DayChangedEventArgs(day));
        }
    }

    public static event EventHandler<DayChangedEventArgs> DayChanged;
}

AND:

public class DayChangedEventArgs : EventArgs
{
    public DayChangedEventArgs(DayOfWeek day)
    {
        this.DayOfWeek = day;
    }

    public DayOfWeek DayOfWeek { get; private set; }
}

Useage: DayChangedNotified.DayChanged += ....

like image 140
BFree Avatar answered Oct 08 '22 05:10

BFree


Instead you could user a Timer and set the timer tick interval to be the time between Now() and midnight.

like image 26
AaronLS Avatar answered Oct 08 '22 05:10

AaronLS