Raise event at a certain time?

I want to be able to let the user enter a time for a specific event to happen.
So for example, At 2:00 a message box displays. The only way I can think of doing this is constantly comparing the current time to the time the event should happen. I really dont like that idea. Does anyone know of any other ways to accomplish this


Answer this question

Raise event at a certain time?

  • Hussein Khalifeh

    You can use a thread. Use thread.sleep() method. Get the difference between the current time and user defined time. Set the thread to sleep mode for that specified duration.

    The thread will automatically start at that time.



  • Alex James

    Hi

    This works fine for me using timer

  • Darren903

    You could use the Timer class. This is from System.Timers namespace but if you have a windows form you could look at that Timer class.

    Set the interval to be from now to when the it needs to be activated. You can use the TotalMilliseconds of a TimeSpan containing the difference between the time to alert the user and DateTime.Now to set the Interval property of the Timer.



  • Scott.Anderson

    I ended up using the TimeSpan and Timer to get this working. Here is the class I ended up using (incase anyone else runs into a similar problem) feel free to add suggestions.

    [code]
    public class ScheduledEvent
    {
    // Our timer
    private Timer timer;
    // Our ScheduleHandler
    public delegate void ScheduleHandler ( );
    // And the event
    public event ScheduleHandler RaiseAction;

    public ScheduledEvent ( DateTime when )
    {
    // If we are already passed when we should do it
    if ( when < DateTime.Now )
    // Dont bother
    throw ( new Exception ( "Cannot schedule an event in history." ) );

    // Get our timespan
    TimeSpan timeSpan = when - DateTime.Now;
    // Create our timer
    timer = new Timer ( timeSpan.TotalMilliseconds );
    // Our elapse function
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    // Start our timer
    timer.Start ( );
    } // End constructor

    private void timer_Elapsed ( object sender, ElapsedEventArgs e )
    {
    // If we have something watching the event
    if ( null != RaiseAction )
    // Do it
    RaiseAction ( );

    // Stop the timer
    timer.Stop ( );
    } // End timer elapsed
    [/code]

  • Raise event at a certain time?