How to delay an execution in Salesforce Apex

Pensacola Mountains
Reading Time: 2 minutes

Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce platform. It was developed by Salesforce and runs natively on their platform. Apex can be used to create custom business logic, automate processes and workflows, and integrate with external systems.

In short, Apex is a programming language for Salesforce that enables developers to build custom applications, automate business processes, and perform other tasks not possible with just point-and-click tools. It can be used to build custom triggers, classes, and interfaces to perform various functions on the Salesforce platform.

In Java, we can use Thread.sleep(1000) to delay the execution by one second. In Apex is not that easy since Salesforce is a multi-tenant environment. By Delaying the execution in the main thread we not only impact the users of our organization but also other Salesforce customers 🤯. That’s why we don’t have that sentence in Apex.


In a multi-tenancy environment, multiple customers share the same application, running on the same operating system, on the same hardware, and with the same data-storage mechanism. The distinction between the customers is achieved during application design, thus customers do not share or see each other’s data.

With some tricks, we can delay the execution without impacting our organization’s resources. Salesforce provides one mechanism to schedule an algorithm for one time or in a recurrent manner.

global class MyScheduler implements Schedulable {
    
    private final Id recordId;
    
    public MyScheduler(Id recordId){
        this.recordId = recordId;
    }
    
    global void execute(SchedulableContext sc){
        System.debug('**** recordId: '+this.recordId+'   date: '+Date.today());

        // ****** Do your logic here ******

        // abort to execute it only once
        System.abortJob(sc.getTriggerId()); 
    }
    
    public static void schedule(){
        String hour = String.valueOf(Datetime.now().hour());
        String min = String.valueOf(Datetime.now().minute() + 1); 
        String ss = String.valueOf(Datetime.now().second());
        
        //parse to cron expression
        String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';
        
        MyScheduler sc = new MyScheduler('0018F00000ABA3AQBX');
        
        String name = 'Submited at: '+String.valueOf(Datetime.now())+ ' next: '+nextFireTime;
        System.debug(name);

        System.schedule(name, nextFireTime, sc);
        
    }
}

How to use it

MyScheduler.schedule();

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: