Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Schedule a task in windows azure worker role

Tags:

c#

azure

I have a simple Azure Worker role running that performs a task every day at 12 PM. Below is the code that accomplishes this.

public override void Run()
{
    try
    {
        while (true)
        {
              int time = Convert.ToInt32(DateTime.Now.TimeOfDay);
              if (time == 12)
              {
                   DoSomethingElse();
              }
        }

    }
    catch (Exception ex)
    {
        Log.Add(ex, true);
    }            
}

Here DoSomethingElse() is a method to send an email at every day 12 PM, and also fires once and only once per day.

How can I implement a scheduler that fire when the time is 12PM and execute DoSomethingElse().

My question is: Is this (above code) is the best method or use any 3rd party tool.

like image 230
Hope Avatar asked Jun 05 '12 12:06

Hope


2 Answers

There are several other questions here that deal with this (and I've marked one above). Having said that, and at the risk of repeating what other answers already state:

In your case, a simple message on a Windows Azure Queue, time-delayed to not show up until noon, would work. This also helps deal with multi-instance scenarios: If you're running two instances of your role, you don't want the same scheduled task running twice, so you need a way to have only one of those instances execute this code. This is easily handled via queue message, or you could run scheduler code on a single instance by using something like a blob lease (which may only have one write-lock against it) as a mutex. This is covered in @smarx's blog post, here.

like image 60
David Makogon Avatar answered Sep 17 '22 13:09

David Makogon


You could also use Quartz.Net http://quartznet.sourceforge.net/ using the blob lease mentioned ab ove is a great way to make sure only one of your instances is hosting tasks.

Using Quartz.Net to Schedule Jobs in Windows Azure Worker Roles

like image 45
Alexandre Brisebois Avatar answered Sep 18 '22 13:09

Alexandre Brisebois