Click here to Skip to main content
Licence CPOL
First Posted 29 Mar 2007
Views 31,840
Downloads 453
Bookmarked 13 times

Midnight Timer - A Way to Detect When it is Midnight

By | 29 Mar 2007 | Article
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DanielBrownAU



Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionsmaller and better Pinmembernimamoi3:51 5 Jul '11  
GeneralException PinmemberMember 283973219:08 30 Jul '09  
GeneralExcellent Pinmemberjrl237@yahoo.com9:14 21 Jul '08  
GeneralBug and Suggestion Pinmemberjerms5522:51 30 Aug '07  
GeneralSystem.Threading.Timer PinmemberStanislav Simicek3:54 2 Apr '07  
GeneralSource code missing PinmemberTBermudez4:41 30 Mar '07  
GeneralRe: Source code missing [modified] PinmemberDaniel@SA6:44 30 Mar '07  
GeneralVotes Pinmembernorm .net1:16 30 Mar '07  
GeneralRe: Votes PinmvpNishant Sivakumar2:46 30 Mar '07  
GeneralRe: Votes PinmemberDaniel@SA2:47 30 Mar '07  
GeneralRe: Votes Pinmembernorm .net2:50 30 Mar '07  
GeneralRe: Votes PinmemberDaniel@SA6:29 30 Mar '07  
GeneralBug Pinmembernicole198222:27 29 Mar '07  
GeneralRe: Bug [modified] PinmemberDaniel@SA22:52 29 Mar '07  
GeneralRe: Bug Pinmemberaridolan2:59 13 May '07  
GeneralRe: Bug PinmemberBruceN15:41 16 Jun '07  
GeneralNice PinmemberZajda8221:55 29 Mar '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 30 Mar 2007
Article Copyright 2007 by DanielBrownAU
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid