3

Possible Duplicate:
Run a code in given time interval

I have a method that runs on the hour. I am currently doing this like so:

while (true)
{
        string rightNow = DateTime.Now.ToString("mm");

        if (rightNow == "00")
        {
            RunMyMethod();
        }
        Thread.Sleep(10000);
}

I have been reliably informed by a friend that I'm an idiot (and generally a bad person), and that I should be using events and delegates to do this instead. I get that, outside the scope of any methods I need declare a delegate with the same return type as my method, and with the same input parameters like so:

public delegate void MyMethodsDelegate();

Then, when I want to use my delegate I instantiate it in the same way I instanciate a class like so:

MyMethodsDelegate foobar = new MyMethodsDelegate(RunMyMethod);

Then I can invoke my delegate like so:

foobar.Invoke();

Ok so I have my delegate setup, how about the event? The event I want to create is 'It's x o'clock', then every time it's x o'clock this kicks off my delegate

Also, am I setting up my delegate correctly?

Thanks

Community
  • 1
  • 1
JMK
  • 27,273
  • 52
  • 163
  • 280

1 Answers1

9

You can use System.Timers.Timer class which executes a delegate asynchronously and raises the Elapsed event when given time interval is elapsed. I would strongly recommend you reading MSDN remarks part for the Timer class, see here.

System.Timers.Timer timer = new Timer(60 * 60 * 100);

Case 1: Subscribe to anonymous method

timer.Elapsed += (s, e) =>
    {
        // callback code here
    };

Case 2: Subscribe to explicitly defined delegate

ElapsedEventHandler handler = (s, e) =>
    {
        // callback code here
    };
timer.Elapsed += handler;

Case 3: Subscribe to the existing method

timer.Elapsed += this.OnHourElapsed;
private void OnHourElapsed(object sender, EventArgs args)
{
    // callback code here
}

Then finally just start a timer

timer.Start();
sll
  • 61,540
  • 22
  • 104
  • 156