0

I am trying to schedule a class every 14 days based on a start date. Example: I want the scheduled job to run on 1st Tuesday of the month and 14 days off that i.e. 3rd Tuesday and then a 5th Tuesday if it exists else runs on the 1st Tuesday of the next month.

P.S. The reason I am not scheduling 3 jobs separately for 1st, 3rd and 5th Tuesday of a month is that if the job runs on the 5th Tuesday, I want it to run on the 2nd Tuesday of the next month (need to maintain the 14 days gap)

Any help is appreciated, Thanks!

2

1 Answer 1

1

Scheduled classes are possible to run not only from Apex Classes -> Schedule Apex, but directly from code, too. You can just chain one after another (after executing any necessary actions). Do not forget to abort current job System.abortJob(sc.getTriggerId());.

You can build cron expression with this tool: https://www.freeformatter.com/cron-expression-generator-quartz.html

Also Salesforce explains how to build crons here.

Overall, your Scheduled Class should look like this:

public without sharing class YourScheduler implements Schedulable {
    public static final String JOB_NAME = 'EVERY_14_DAYS_JOB';

    public void execute(System.SchedulableContext sc) {
        //run any necessary actions here

        System.abortJob(sc.getTriggerId());

        Datetime workTime = System.now().addDays(14);
        String CRONEXP = '' + workTime.second() + ' ' + workTime.minute() + ' ' + workTime.hour()
                + ' ' + workTime.day() + ' ' + workTime.month() + ' ? ' + workTime.year();

        System.schedule(JOB_NAME, CRONEXP, new YourScheduler());
    }
}

To make it run for the first time on the specific Datetime (Date), execute this code in Amomymous Block:

Datetime workTime = Datetime.newInstance(2021, 8, 3, 0, 0, 0); // first Tuesday of August
String CRONEXP = '' + workTime.second() + ' ' + workTime.minute() + ' ' + workTime.hour()
                + ' ' + workTime.day() + ' ' + workTime.month() + ' ? ' + workTime.year();

System.schedule(YourScheduler.JOB_NAME, CRONEXP, new YourScheduler());

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .