Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c# - 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)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...