Loading
Scalability
ApexGuru Antipattern: Busy Loop Delay

ApexGuru Antipattern: Busy Loop Delay

Busy loops that introduce a delay aren’t efficient and lead to performance issues. They waste CPU resources due to continuous loop execution. Governor limit breaches cause transaction failures. For delayed execution, use Salesforce alternatives like scheduling systems in Apex. If the delay is due to an async job, use System.enqueueJob with a delay parameter.

Scope

Detection only

Detection Example

Apex
public class JobScheduler {
    public void scheduleJobWithDelay() {
        Integer delayTime = 10; // Delay in seconds
        DateTime startTime = System.now();        
        // Busy loop to create a delay
        while (System.now() < startTime.addSeconds(delayTime)) {
            // Do nothing (busy wait)
        }     
        // Enqueue the Queueable job after the delay
        ID jobId = System.enqueueJob(new MyQueueableJob());
    }
}
 
Indlæser
Salesforce Help | Article