DateChange在午夜举行的活动

时间:2011-12-12 19:55:31

标签: c# c#-4.0

  

可能重复:
  Background Worker Check For When It's Midnight?

是否有可以注册的SystemEvent,并且会在午夜更新日期时发布?

2 个答案:

答案 0 :(得分:11)

这是我用来处理这个问题的课程。它类似于@sll的答案,但考虑到系统时间的变化,也会触发每个午夜,而不是仅触发一次。

static class MidnightNotifier
{
    private static readonly Timer timer;

    static MidnightNotifier()
    {
        timer = new Timer(GetSleepTime());
        timer.Elapsed += (s, e) =>
        {
            OnDayChanged();
            timer.Interval = GetSleepTime();
        };
        timer.Start();

        SystemEvents.TimeChanged += OnSystemTimeChanged;
    }

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

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

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

    public static event EventHandler<EventArgs> DayChanged;
}

由于它是静态类,您可以使用以下代码订阅事件:

MidnightNotifier.DayChanged += (s, e) => { Console.WriteLine("It's midnight!"); };

答案 1 :(得分:2)

Windows任务计划程序通常是在指定日期启动某些内容的正确方法。

但如果你真的在寻找一个或同等的事件:

var timer = new System.Timers.Timer((DateTime.Today.AddDays(1) – DateTime.Now).
    TotalMillisecond);
timer.Elapsed += new ElapsedEventHandler(OnMidnight);
timer.Start();