Search code examples
cronquartz-schedulerquartz.net

Generate cron expression for weekly and repeat every n weeks


I am trying to create weekly cron expression which will execute every week on selected days like Mon,Tue. Along with this I have to implement repeat every functionality with it. So that trigger would be fired after repeat every interval.

eg. I have to execute job every Monday and alternate week in case when interval value is 2. When interval value is 3 I have to execute this job every Monday after 2 weeks.

This functionality is easily achieved in case of Daily or monthly, but I am not able to find it in case of weekly. eg. Cron for daily and repeat every interval as 3 0 0 12 1/3 * ? *


Solution

  • You cannot do that with cron expressions.

    Your best bet is to use the WithCalendarIntervalSchedule() method to specify the intervals in weeks you want the trigger to happen:

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .StartNow()
                .WithCalendarIntervalSchedule(
                    scheduleBuilder => scheduleBuilder.WithIntervalInWeeks(3))
                .Build();
    

    Instead of StartNow(), you will also have to use StartAt(), and find a way to get the date of the next Monday (using for example Jon Skeet answer from this question: Datetime - Get next tuesday)