Quartz.Net Jobs in Azure WebRole

别说谁变了你拦得住时间么 提交于 2019-11-29 07:25:12
BitKFu

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();
    }
}

The answer above helped me a lot, but it has one hickup, the OnStart method is not overwritten so the method is never called. Also it should be Boolean and not void. This worked for me:

public override bool OnStart()
{
    // For information on handling configuration changes
    // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

    workerThread = new MyWorkerThread();
    Thread thread = new Thread(workerThread.Start);
    thread.Start();

    return base.OnStart();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!