Thursday, February 4, 2021

How to Run Schedule Apex only once or every few mins

Using Scheduled Apex in UI, you cannot set a scheduled class to run only once. It's always recurring. So, you'll need to use System.scheduled via the system log to implement a workaround.

Example code for running a job 10 minutes from now only once


String hour = String.valueOf(Datetime.now().hour());
String min = String.valueOf(Datetime.now().minute() + 10); 
String ss = String.valueOf(Datetime.now().second());

//parse to cron expression
String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';

MyScheduledJob s = new MyScheduledJob(); 
System.schedule('Job Started At ' + String.valueOf(Datetime.now()), nextFireTime, s);


Abort the job by adding a finish method to your class that implements the Schedulable Interface. This stops the job from running more than once.

Example code to abort the job


global void finish(Database.BatchableContext BC)
{
// Get the ID of the AsyncApexJob representing this batch job from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email ..... FROM AsyncApexJob WHERE Id = 
:BC.getJobId()];

//then use the active job id and abort it
system.abortJob(a.id);
}


Example code for running a job every 2 mins


Integer frequency = 2;
Integer totalIterations = 60/frequency - 1;
for(Integer i = 0; i <= totalIterations; i++){
Integer count = i*frequency;
String minuteString = (count < 10) ? '0' + count : '' + count;
System.schedule('Scheduled Job ' + i, '0 ' + minuteString + ' * * * ?', new MyScheduledJob());
}