Skip to content

Instantly share code, notes, and snippets.

@sbutterfield
Created October 27, 2020 22:36
Show Gist options
  • Save sbutterfield/96a4794e64dd846046860e8eff1d75cd to your computer and use it in GitHub Desktop.
Save sbutterfield/96a4794e64dd846046860e8eff1d75cd to your computer and use it in GitHub Desktop.
Apex job runner class to recursively execute scheduled job ever "n" minutes
global without sharing class JobRunner implements Schedulable {
Integer intervalMinutes;
public JobRunner(Integer intervalMinutes) {
this.intervalMinutes = intervalMinutes;
}
public void execute(SchedulableContext sc) {
// Re-schedule ourself to run again in "intervalMinutes" time
DateTime now = DateTime.now();
DateTime nextRunTime = now.addMinutes(intervalMinutes);
String cronString = '' + nextRunTime.second() + ' ' + nextRunTime.minute() + ' ' +
nextRunTime.hour() + ' ' + nextRunTime.day() + ' ' +
nextRunTime.month() + ' ? ' + nextRunTime.year();
System.schedule(JobRunner.class.getName() + '-' + now.format(), cronString, new JobRunner(intervalMinutes));
// Abort the current job
Id jobId = sc.getTriggerId();
System.abortJob(jobId);
// Launch a batch job or call a future method to do the actual work
Database.executeBatch(new SomeBatchJob());
}
}
@sbutterfield
Copy link
Author

@nitish771,
In this case, it's an example of being able to execute a scheduled apex job every n-minutes or even more frequently (although because SC is executed on a message queue, you should never execute less than a minute...) by calling a job (batch apex, in this case) and dynamically rescheduling a new instance of a scheduled job at a specific time. That's the only way to get scheduled execution every n-minutes without using multiple scheduled apex jobs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment