Search code examples
c#.netquartz.nettopshelf

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


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

Following this example I am building my jobs with

                s.ScheduleQuartzJob(q =>
                    q.WithJob(() => JobBuilder.Create<MyJob>().Build())
                    .AddTrigger(() => TriggerBuilder.Create()
                        .WithSimpleSchedule(builder => builder
                            .WithIntervalInSeconds(5)
                            .RepeatForever())
                        .Build())
                );

which fires my job every five seconds even if the previous is still running. What I really want to achive is to start a job and after the completion wait five seconds and start again. Is this possible or do I have to implement my own logic (for example via a static variable).


Solution

  • The JobListener solution is a very powerful and flexible way to reschedule your job after completion. Thanks to Nate Kerkhofs and stuartd for the input.

    In my case it was sufficient to decorate my Job class with the DisallowConcurrentExecution attribute since I don't have different instances of my job

    [DisallowConcurrentExecution]
    public class MyJob : IJob
    {
    }
    

    FYI: Using a JobListerener with TopShelf.Quartz the code could look like this

    var jobName = "MyJob";
    var jobKey = new JobKey(jobName);
    
    s.ScheduleQuartzJob(q =>
               q.WithJob(() => JobBuilder.Create<MyJob>()
                    .WithIdentity(jobKey).Build())
                .AddTrigger(() => TriggerBuilder.Create()
                    .WithSimpleSchedule(builder => builder
                        .WithIntervalInSeconds(5)
                    .Build())
    
    var listener = new RepeatAfterCompletionJobListener(TimeSpan.FromSeconds(5));
    var listenerManager = ScheduleJobServiceConfiguratorExtensions
          .SchedulerFactory().ListenerManager;
    listenerManager.AddJobListener(listener, KeyMatcher<JobKey>.KeyEquals(jobKey));
    

    If you are using TopShelf.Quartz.Ninject (like I do) don't forget to call UseQuartzNinject() prior to calling ScheduleJobServiceConfiguratorExtensions.SchedulerFactory()