rasputino
rasputino

Reputation: 799

How to repeat a Job until is completed in Quartz.Net

I want to repeat a Job in Quartz.Net until it's correctly completed. I tried something like this:

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

With this simple trigger:

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

It should stop when the "Success!" log statment is executed, and repeats when it fails. I tried this too but it doesn't work with Quartz.Net 3. Any ideas?

Upvotes: 1

Views: 1233

Answers (1)

rasputino
rasputino

Reputation: 799

I found the problem, the try/catch should be inside the task:

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;

        }


    }
}

Upvotes: 2

Related Questions