Background Worker Check For When It's Midnight?

三世轮回 提交于 2019-11-28 00:04:44

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 += ....

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

you can use Quartz to schedule that. Maybe is like a cannon to kill a mosquito in this scenario, but that's is the only scheduling job framework i know and works excellent.

Don't use polling. Instead, set up a timer task, set it to fire at midnight, and add an event to process.

 TimeSpan timeBetween = DateTime.Today.AddDays(1) - DateTime.Now;

 System.Timers.Timer t = new System.Timers.Timer();
 t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
 t.Interval = 1000 * timeBetween.Seconds;
 t.Start();

I have no idea why polling solutions were voted up when Microsoft solved this type of problem years ago by adding a windows service to handle timing. Just create a scheduled task to run the exe. No extra overhead.

I'm a little confuse about why you need a WinForm, will it be running at midnight? If all you need is some sort process to run, use the windows scheduler to run it at midnight. (On XP, but I believe Win server should be similar)Control Panel -> Scheduled Tasks -> Add Scheduled Task -> Fill out the wizard. Save you a lot of coding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!