Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quartz.Net Jobs in Azure WebRole

I'm currently porting a WCF Service Project over to an Azure Role. Until now the library containing the service also hosted a Quartz.Net JobFactory for some lightweight background processing (perdiodically cleaning up stale email confirmation tokens). Do I have to move that code into a seperate worker role?

like image 613
Oliver Weichhold Avatar asked Jun 06 '11 07:06

Oliver Weichhold


1 Answers

No you don't have to setup a separate worker role.

You simply have to start a background thread in your OnStart() Method of your Web Role. Give that thread a Timer object that executes your method after the given timespan.

Due to this you can avoid a new worker role.

class MyWorkerThread 
{
    private Timer timer { get; set; }
    public ManualResetEvent WaitHandle { get; private set; }

    private void DoWork(object state)
    {
        // Do something
    }

    public void Start()
    {
        // Execute the timer every 60 minutes
        WaitHandle = new ManualResetEvent(false);
        timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(60));

        // Wait for the end 
        WaitHandle.WaitOne();
    }
}

class WebRole : RoleEntryPoint
{
    private MyWorkerThread workerThread;

    public void OnStart()
    {
        workerThread = new MyWorkerThread();
        Thread thread = new Thread(workerThread.Start);
        thread.Start();
    }

    public void OnEnd()
    {
        // End the thread
        workerThread.WaitHandle.Set();
    }
}
like image 170
BitKFu Avatar answered Oct 22 '22 00:10

BitKFu