How to delay an execution in Salesforce Apex

Using Schedulable interface to delay an execution in Apex


Andres Canavesi
Jun 10, 2022
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.
featured image
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 multitenancy environment, multiple customers share the same application, running on the same operating system, on the same hardware, 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.

Multitenancy in Wikipedia
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();
      
    
Photo by Erik Mclean on Unsplash