Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Midnight Timer - A Way to Detect When it is Midnight

0.00/5 (No votes)
29 Mar 2007 1  
An article on how to detect when it is midnight

Introduction

I'm sure that a large percentage of developers have wished for a way to detect when it is midnight on a machine and execute code which updates something simple and non complex (i.e. display dates, instead of "Today" you would want it to show "Yesterday" and so forth).

I pondered over this for some time until I had inspiration one late night. Let's use a Timer to do it, but with some intelligence.

Background

While working on a larger project, I needed a way to ensure that an event would fire which would execute code to update the displayed days (much how Outlook displays emails by date) at midnight.

I thought of various methods to accomplish this. Check the datetime every second.. no, Check the time ever x hours... no... Just loop until midnight is reached... no!

Each way I thought of included heavy looping or polling in order to check the time to know when it turns midnight. So a new approach was needed.

I realised that I could use a system Timer to achieve what I wanted without reinventing the wheel.

Using the Code

I've designed the code in a simplistic way in order for you to use the code more effectively.

I have contained the logic in a single class, which has only a single public method of Start() and the event property.

When the class is first executed via the Start() method, the code obtains a datetime of the current time, then gets a datetime object of midnight and subtracts the 2 times in order to give a time until it is midnight.

With this time, it sets the timer interval and starts the timer. Now when the interval is reached and the timer fires its event, I reset the timer using the same process. This will make the interval for 24. When this timer expires, it is then reset and repeated indefinitely.

To use the class in your code, simply add these lines.

Insert the following into the method you wish to call the Timer from:

MidnightTimer m_MidnightTimer = new MidnightTimer();
m_MidnightTimer.TimeReached += new TimeReachedEventHandler(m_MidnightTimer_TimeReached);

Add the Event Handler method:

void m_MidnightTimer_TimeReached(DateTime Time)
{
    // do something here...
}

Let's look at the main piece behind this code:

public void Start()
{
    // Subtract the current time, from midnight (tomorrow).
    // This will return a value, which will be used to
    // SetTimer the Timer interval
    TimeSpan ts = GetMidnight().Subtract(DateTime.Now);

    // We only want the Hours, Minutes and Seconds until midnight
    TimeSpan tsMidnight = new TimeSpan(ts.Hours, ts.Minutes, ts.Seconds);

    // Set the Timer
    m_timer = new Timer(tsMidnight.TotalMilliseconds);

    // Set the event handler
    m_timer.Elapsed += new ElapsedEventHandler(t_Elapsed);

    // Start the timer
    m_timer.Start();
}

private void t_Elapsed(object sender, ElapsedEventArgs e)
{
    // now raise an event
    OnTimeReached();

    // Stop the original timer
    m_timer.Stop();

    // reset the timer
    this.Start();
}

What the Start() method actually does is obtain the current time and midnight of the next day (DateTime.Now.Day+1) and subtracts them to give us how many hours, minutes, seconds until midnight occurs. This is the value we use to set the initial timer to fire at midnight.

Now after a few hours pass by and it is midnight, the timer fires and recalls Start() (as well as stops the original timer, etc.) and repeats the process of getting the time now, and the time of the next midnight (in this case, 24 hours) and resets the timer.

Feedback

Feedback is most welcome! In fact I insist on it!

If you have any improvements or ideas on how to improve this code, please speak up and voice your opinion! It's a great way to learn!

History

  • 1.0.0.0 - 30/03/2007 - Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here