How do I force a quartz.net job to restart intervall after completion

后端 未结 4 949
醉话见心
醉话见心 2021-01-22 19:27

I have a project where I use TopShelf and TopShelf.Quartz

Following this example I am building my jobs with

                s.         


        
4条回答
  •  长情又很酷
    2021-01-22 19:54

    A job listener as proposed by @NateKerkhofs will work, like this:

    public class RepeatAfterCompletionJobListener : IJobListener
    {
        private readonly TimeSpan interval;
    
        public RepeatAfterCompletionJobListener(TimeSpan interval)
        {
            this.interval = interval;
        }
    
        public void JobExecutionVetoed(IJobExecutionContext context)
        {
        }
    
        public void JobToBeExecuted(IJobExecutionContext context)
        {
        }
    
        public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {
           string triggerKey = context.JobDetail.Key.Name + ".trigger";
    
            var trigger = TriggerBuilder.Create()
                    .WithIdentity(triggerKey)
                    .StartAt(new DateTimeOffset(DateTime.UtcNow.Add(interval)))
                    .Build();
    
            context.Scheduler.RescheduleJob(new TriggerKey(triggerKey), trigger);
        }
    
        public string Name
        {
            get
            {
                return "RepeatAfterCompletionJobListener";
            }
        }
    }
    

    Then add the listener to the scheduler:

    var jobKey = "myJobKey";
    var schedule = new StdSchedulerFactory().GetScheduler();
    listener = new
       RepeatAfterCompletionJobListener(TimeSpan.FromSeconds(5));
    
    schedule.ListenerManager.AddJobListener
             (listener, KeyMatcher.KeyEquals(new JobKey(jobKey)));
    
    var job = JobBuilder.Create(MyJob)
                    .WithIdentity(jobKey)
                    .Build();
    
    // Schedule the job to start in 5 seconds to give the service time to initialise
    var trigger = TriggerBuilder.Create()
                    .WithIdentity(CreateTriggerKey(jobKey))
                    .StartAt(DateTimeOffset.Now.AddSeconds(5))
                    .Build();
    
    schedule.ScheduleJob(job, trigger);
    

    Unfortunately I don't know how to do this (or if it can be done) with the fluent syntax used by Typshelf.Quartz library, I use this with TopShelf and regular Quartz.Net.

提交回复
热议问题