Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event for DateChange at midnight [duplicate]

Tags:

c#

c#-4.0

Possible Duplicate:
Background Worker Check For When It's Midnight?

Is there a SystemEvent which I can register to and which will be published at midnight, when the Date has changed?

like image 369
BennoDual Avatar asked Dec 12 '11 19:12

BennoDual


2 Answers

Here's a class I use to handle this. It's similar to @sll's answer, however takes into account the system time changing and also will trigger each midnight instead of only once.

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;
}

Since it's a static class, you can subscribe to the event using code like:

MidnightNotifier.DayChanged += (s, e) => { Console.WriteLine("It's midnight!"); };
like image 50
Ben Hoffstein Avatar answered Sep 19 '22 19:09

Ben Hoffstein


The Windows Task Scheduler is generally the proper way to start something at a specified date.

But if you are really searching for an event or equivalent:

var timer = new System.Timers.Timer((DateTime.Today.AddDays(1) – DateTime.Now).
    TotalMillisecond);
timer.Elapsed += new ElapsedEventHandler(OnMidnight);
timer.Start();
like image 21
Otiel Avatar answered Sep 19 '22 19:09

Otiel