Azure WebRole中的Quartz.Net作业

时间:2011-06-06 07:47:18

标签: azure azure-worker-roles

我目前正在将WCF服务项目移植到Azure角色。到目前为止,包含该服务的库还托管了一个Quartz.Net JobFactory,用于一些轻量级后台处理(定期清理过时的电子邮件确认令牌)。我是否必须将该代码转换为单独的工作者角色?

2 个答案:

答案 0 :(得分:9)

不,您不必设置单独的工作人员角色。

您只需在Web角色的OnStart()方法中启动后台线程即可。为该线程提供一个Timer对象,该对象在给定的时间跨度后执行您的方法。

因此,您可以避免新的工作人员角色。

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

答案 1 :(得分:0)

上面的答案对我有很大的帮助,但它有一个hickup,OnStart方法没有被覆盖,因此永远不会调用该方法。它也应该是布尔值而不是无效。这对我有用:

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();
}
相关问题