tags:

views:

1772

answers:

8

Is there a way to get notification of date change in c#?

I have a requirement where I have to do something when the system date is changed.

I found that SystemsEvent.TimeChanged is an event you can hook into, however it is only fired only when user has changed the time.

+5  A: 

Would this be better handled by having a scheduled task/cron job that runs at midnight?

Harper Shelby
+2  A: 

You could implement this (admittedly poorly) as follows:

Write a very lightweight class which simply stores the current date. Start it in a separate thread and make it periodically check the date, then sleep for a large amount of time (in fact, you could make it sleep for just longer than the time left until midnight). If the date has changed, make it call a callback function in the main part of your app.

Like I said, this doesn't seem like a brilliant solution to your problem and there are probably much better ways of doing it.

xan
There's really no reason to waste a thread on this. Just add a callback as Darryl Braaten suggests. Callbacks are executed by a threadpool thread, so you don't need to have a thread hanging around for this.
Brian Rasmussen
A: 

Your app could run a loop that sleeps for a minute, then checks the date. If it's different than last time, run your logic.

But I agree that this scenario would be better handled with a scheduled task.

recursive
A: 

Not sure if there's an event for this, but if not, a usable workaround would be to fire a timer every minute, and if the time changed more than 5 minutes in between calls, then you can be pretty sure that the time has been changed in some way or another. You could go more fine grained if you like, by firing the event every second, and checking the time difference, of more than 10 seconds, but every minute would probably be sufficient.

Kibbee
+1  A: 

You might be looking for System.Threading.Timer. It will fire at an interval you set.

Darryl Braaten
+1  A: 

Assuming what you are asking for is to know when a user changes the date\time of their PC, the only way I know to do this is to monitor the EventLog, something like this:

    static System.Diagnostics.EventLog log = new EventLog("System");

    public Form1()
    {
        log.EntryWritten += new EntryWrittenEventHandler(log_EntryWritten);
        log.EnableRaisingEvents = true;
    }

    void log_EntryWritten(object sender, EntryWrittenEventArgs e)
    {
        if (e.Entry.InstanceId == 1 && e.Entry.EntryType == EventLogEntryType.Information)
            Console.WriteLine("Test");
    }
Brian Rudolph
A: 

Or use this for DST info: TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Today.Year)

+1  A: 

The system broadcasts a WM_TIMECHANGE message when the user changes the system date/time. The correct way to handle this is to handle that message. I suspect the .net event SystemEvents.TimeChanged is just a wrapper around this.

Will Rickards