Loading

Run Scheduled Apex job only once

Veröffentlichungsdatum: Oct 13, 2022
Beschreibung
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
Lösung

NOTE: The code provided here won't work for the last 10 minutes of every hour.


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);
}
Nummer des Knowledge-Artikels

000382128

 
Laden
Salesforce Help | Article