如何重复作业直到在Quartz.Net中完成

时间:2018-08-31 11:56:57

标签: c# quartz.net

我想在Quartz.Net中重复一个作业,直到正确完成为止。我尝试过这样的事情:

using Common.Logging;
using Quartz;
using System;
using System.Threading.Tasks;

namespace MyNamespace
{
    [DisallowConcurrentExecution]
    public class ExampleJob : IJob
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(ExampleJob));

        public Task Execute(IJobExecutionContext context)
        {
            ISimpleTrigger trigger = (ISimpleTrigger)context.Trigger;
            try
            {    
                var myTask = new Task(() =>
                {
                    _log.Info("Starts " + context.JobDetail.Key.Name);

                    if (trigger.TimesTriggered < 3)
                    {
                        _log.Info("I'm going to fail " + trigger.TimesTriggered + " " + context.JobDetail.Key.Name);
                        throw new NotImplementedException();
                    }

                    _log.Info("Success! " + trigger.TimesTriggered + " " + context.JobDetail.Key.Name);
                });
                myTask.Start();
                return myTask ;
            }
            catch(Exception exc)
            {
               throw new JobExecutionException(exc) {RefireImmediately = true};
            }
        }
    }
}

通过这个简单的触发器:

    ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity("trigger, "group")
        .StartNow()
        .Build();

它应该在“成功!”时停止。日志语句已执行,并在失败时重复执行。我也尝试过this,但不适用于Quartz.Net3。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我发现了问题,try / catch应该在任务内部:

using Common.Logging;
using Quartz;
using System;
using System.Threading.Tasks;

namespace MyNamespace
{
    [DisallowConcurrentExecution]
    public class MyJob : IJob
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(MyJob));

        public Task Execute(IJobExecutionContext context)
        {
            var myTask = new Task(() =>
            {
                try
                {
                    _log.Info("Start!" + context.JobDetail.Key.Name);

                    if (context.RefireCount < 3)
                    {
                        _log.Info("Fails! " + context.RefireCount + " " + context.JobDetail.Key.Name);
                        throw new NotImplementedException();
                    }

                    _log.Info("Ok! " + context.RefireCount + " " + context.JobDetail.Key.Name);
                }
                catch (Exception ex)
                {
                    throw new JobExecutionException(ex) { RefireImmediately = true };
                }
            });
            myTask.Start();
            return myTask;

        }


    }
}