Loading

Run Scheduled Apex job only once

Publiceringsdatum: May 3, 2026
Beskrivning

When using the Salesforce UI to schedule an Apex class, there is no option to configure the scheduled class to run only once — it always recurs. 

To schedule an Apex job that runs a single time and does not repeat, use the System.schedule() method via the Developer Console's Execute Anonymous window (also known as the system log). Additionally, to ensure the job does not run a second time, you can programmatically abort it in the finish() method of your class.

Note: The code provided in this article will not work for the last 10 minutes of every hour due to minute arithmetic overflow.

Lösning

Example: Schedule a Job to Run 10 Minutes From Now (One Time Only)

The following code calculates a one-time execution time 10 minutes from the current time and schedules the job using a CRON expression. Execute this code in the Developer Console's Execute Anonymous window:

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);

 

Example: Abort the Job After First Execution

To prevent the scheduled job from running more than once, implement a finish() method in your class that implements the Schedulable interface. The finish() method retrieves the job ID from the BatchableContext, queries the AsyncApexJob object for the current job, and then aborts it:

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);
}
Knowledge-artikelnummer

000382128

 
Laddar
Salesforce Help | Article