Getting notified when the datetime changes in c#

霸气de小男生 提交于 2019-12-05 17:45:41

Can you simply work out the number of seconds until midnight, and then sleep for that long?

@OddThinking's answer will work (you could set a timer for the interval instead of sleeping). Another way would be to set a timer with a 1 minute interval and simply check if the system date has changed. Since you are only executing some lightweight code once a minute, I doubt the overhead would be noticable.

public void Main()
{

    var T = new System.Timers.Timer();

    T.Elapsed += CallBackFunction;

    var D = (DateTime.Today.AddDays(1).Date - DateTime.Now);

    T.Interval = D.TotalMilliseconds;

    T.Start();

}

private void CallBackFunction(object sender, System.Timers.ElapsedEventArgs e)
{

    (sender as System.Timers.Timer).Interval = (DateTime.Today.AddDays(1).Date - DateTime.Now).TotalMilliseconds;

}

Try looking into monitoring WMI events, you should be able to create a Wql event query that monitors the day of week change (i.e. ManagementEventWatcher etc) and then setup an event handler that fires when the event arrives.

using System;
using System.Management;

class Program
{
    public static void Main()
    {
        WqlEventQuery q = new WqlEventQuery();
        q.EventClassName = "__InstanceModificationEvent ";
        q.Condition = @"TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 22 AND TargetInstance.Minute = 7 AND TargetInstance.Second = 59";

        Console.WriteLine(q.QueryString);

        using (ManagementEventWatcher w = new ManagementEventWatcher(q))
        {
            w.EventArrived += new EventArrivedEventHandler(TimeEventArrived);
            w.Start();
            Console.ReadLine(); // Block this thread for test purposes only....
            w.Stop();
        }
    }

    static void TimeEventArrived(object sender, EventArrivedEventArgs e)
    {
        Console.WriteLine("This is your wake-up call");
        Console.WriteLine("{0}", new
        DateTime((long)(ulong)e.NewEvent.Properties["TIME_CREATED"].Value));
    }
}

How about a thread that checks for change in date. The thread can have some events that the controls that need this information can subscribe to.

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