Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate an alert at a specific time in C#?

Tags:

c#

winforms

clock

How can i generate an event at a specific time? For example, say I want to generate an alert at 8:00 AM that informs me its 8:00 AM (or an event that informs me of the current time at any given time).

like image 337
Mobin Avatar asked Aug 18 '09 23:08

Mobin


3 Answers

Use the System.Threading.Timer class:

var dt = ... // next 8:00 AM from now
var timer = new Timer(callback, null, dt - DateTime.Now, TimeSpan.FromHours(24));

The callback delegate will be called the next time it's 8:00 AM and every 24 hours thereafter.

See this SO question how to calculate the next 8:00 AM occurrence.

like image 53
dtb Avatar answered Oct 22 '22 14:10

dtb


Elaborating on dtb's answer this is how I implemented it.

  private void Form1_Load(object sender, EventArgs e)
    {
        System.Threading.TimerCallback callback = new TimerCallback(ProcessTimerEvent);

        //first occurrence at
        var dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0);

        if (DateTime.Now < dt)
        {
            var timer = new System.Threading.Timer(callback, null, 
                                               //other occurrences every 24 hours
                            dt - DateTime.Now, TimeSpan.FromHours(24));
        }

    }

    private void ProcessTimerEvent(object obj)
    {
        MessageBox.Show("Hi Its Time");
    }
like image 20
Thunder Avatar answered Oct 22 '22 15:10

Thunder


Does the alert have to be generated by your program? An alternate approach is to use a Scheduled Task (in Windows) to generate the alert. You might need to write a small program that gathers any information from your main application's data files etc.

There are a couple of main benefits to using this approach:

  1. You don't have to write any code to support the feature. You make use of something built into the operating system. The example is for Windows, but other OSes have the same feature. You can concentrate your development and support effort on your own code.
  2. Your main application doesn't have to be running for the task to fire.
like image 1
ChrisF Avatar answered Oct 22 '22 15:10

ChrisF