What Fundamental Aspects Define Async Apex Methods In 2024?

Let’s talk about Async Apex Method. Before that let’s see some basics of async process.

Many of the time while coding we want a process or function to run after the availability of resources, in such case async methods came into picture, these methods will run after the required resources will be available, also it will not affect the flow of execution of rest of the code. An asynchronous process executes a task in the background. User doesn’t have to wait for the task to finish. We basically use async apex for :

  • Callouts to an external system
  • Operations that require higher limits
  • Code that needs to run at a certain time.

After discussing the definition and purpose let’s talk about the different types of Async Apex Methods.

  • Future Method

A Future method is denoted by the @future annotation in Apex. This annotation informs Salesforce that the method should be executed asynchronously. Future methods are useful for scenarios where you want to perform tasks outside the scope of the current transaction, avoiding any impact on the user experience or transaction response time.

Sample Code:

Let’s create a simple example to demonstrate a Future method. Suppose we want to create a method that updates the status of a record asynchronously. Here’s how you can do it:

public class AsyncApexExample {
    // This is a future method
    @future
    public static void updateRecordStatusAsync(Id recordId, String newStatus) {
        // Retrieve the record to update
        MyObject__c myRecord = [SELECT Id, Status__c FROM MyObject__c WHERE Id = :recordId LIMIT 1];
        // Update the status
        myRecord.Status__c = newStatus;
      // Update the record
        update myRecord;
    }
}

In this example, the updateRecordStatusAsync method is annotated with @future. It takes two parameters: recordId, the Id of the record to update, and newStatus, the new status value to set. The method retrieves the record, updates the status, and then updates the record asynchronously.

Calling the Future Method

You can call a future method from other Apex code like this:

// Assuming you have the record Id and new status values
Id recordIdToUpdate = 'a1X1I0000012345'; // Replace with your actual record Id
String newStatusValue = 'Completed'; // Replace with your desired status value
// Call the future method
AsyncApexExample.updateRecordStatusAsync(recordIdToUpdate, newStatusValue);
// Continue with other logic if needed

When you call updateRecordStatusAsync, Salesforce processes the method asynchronously, allowing the main transaction to continue without waiting for the update to complete. This is beneficial when you want to perform tasks that might take time, such as making callouts or handling large data sets, without affecting the performance of the user interface.

  • Batch Apex

Batch Apex is implemented by defining a class that implements the Database.Batchable interface. This interface requires the implementation of three methods: start, execute, and finish. The start method gathers the records to be processed, the execute method processes the records in chunks, and the finish method is called once all chunks have been processed.

Batch Apex provides a scalable and efficient way to handle large volumes of data in Salesforce, ensuring that your processing logic can be executed without hitting governor limits.

Sample Code:

Let’s create a simple example where we update the status of a custom object (MyObject__c) asynchronously in batches:

public class BatchApexExample implements Database.Batchable<SObject> {
    // Start method to gather records
    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator('SELECT Id, Status__c FROM MyObject__c WHERE Status__c = \'Pending\'');
    }
    // Execute method to process records in chunks
    public void execute(Database.BatchableContext context, List<MyObject__c> records) {
        for (MyObject__c record : records) {
            // Perform some processing (e.g., updating the status)
            record.Status__c = 'Processed';
        }
        // Update the processed records
        update records;
    }
    // Finish method to perform any post-processing tasks
    public void finish(Database.BatchableContext context) {
        // Perform any cleanup or post-processing tasks here
    }
}

Running the Batch Apex Job

To run the Batch Apex job, you can use the following anonymous Apex code:

// Instantiate the batch class
BatchApexExample myBatch = new BatchApexExample();
// Start the batch job
Database.executeBatch(myBatch, 200); // The second parameter (200) is the size of each batch

In this example, the start method queries records with a specific status (‘Pending’), and the execute method updates the status of these records in chunks. The finish method can be used for any cleanup or post-processing tasks after all records have been processed.

  • Queueable Apex

Queueable Apex allows you to chain multiple jobs together and provides a more flexible alternative to Future Methods.Queueable Apex is designed for more immediate and flexible execution. Here’s an example where we chain two Queueable jobs:

public class QueueableExample implements Queueable {
    public void execute(QueueableContext context) {
        // Your queueable logic goes here
        System.debug('Queueable job executed successfully');
    }
}
// Enqueue the first job
QueueableExample job1 = new QueueableExample();
System.enqueueJob(job1);
// Enqueue the second job after the first job completes
QueueableExample job2 = new QueueableExample();
System.enqueueJob(job2);

In this example, the QueueableExample class implements the Queueable interface, and the execute method contains the logic to be executed asynchronously. The second job is enqueued after the first job completes, allowing you to chain multiple jobs together.

  • Scheduled Apex:

Scheduled Apex allows you to schedule the execution of your code at a specific time or on a recurring basis. Here’s an example where we schedule a class to run every day at a specific time:

global class ScheduledApexExample implements Schedulable {
    global void execute(SchedulableContext sc) {
        // Your scheduled logic goes here
        System.debug('Scheduled job executed successfully');
    }
}
// Schedule the job to run every day at 2 AM
ScheduledApexExample scheduledJob = new ScheduledApexExample();
String cronExpression = '0 0 2 * * ?'; // Cron expression for daily execution at 2 AM
System.schedule('MyScheduledJob', cronExpression, scheduledJob);

In this example, the ScheduledApexExample class implements the Schedulable interface, and the execute method contains the logic to be executed at the scheduled time. The job is scheduled using the System.schedule method, with a cron expression specifying the execution schedule.