Understanding the Basics of Asynchronous Apex

Understanding Asynchronous Apex

Asynchronous terms mean something not existing or occurring at the same time. In Salesforce, Asynchronous Apex refers to processes that run in the background without requiring the user to wait for completion. The Apex code executes independently in a separate thread, allowing asynchronous tasks to be completed in its own time while the main program keeps running without interruption.

These processes are particularly useful for scenarios where immediate execution is not necessary or bypassing certain constraints is required.

Asynchronous vs synchronous processing

Key Understandings –

  • An asynchronous process executes a task in the background.
  • The user doesn’t have to wait to complete the task.
  • It is executed when resources are available.
  • Used for
    • Callouts to external.
    • Operations that require higher limits.
    • Code that needs to run at a specific time.

Governor Limits for Asynchronous Processes

In case you’re new to the term, “governor limits” are restrictions enforced by the Salesforce platform to ensure fair and efficient resource usage by applications. These limits prevent any single transaction, request, or user from monopolizing shared resources or causing performance issues for other users.

They are designed to maintain the stability and scalability of the Salesforce platform. Therefore, Understanding and adhering to governor limits is crucial for building reliable and efficient applications on the Salesforce platform. Violating governor limits can lead to errors or exceptions being thrown by the platform, potentially disrupting the application’s functionality. Below are some limits imposed for various asynchronous aspects.

Governor limits for Asynchronous processes

You can view a complete list here – Apex Governor Limits by Salesforce.

Advantages of Asynchronous Apex

#1 Higher Limits

Salesforce allows extended governor and execution limits for asynchronous tasks compared to those applicable to synchronous transactions. This allows for more complex and resource-intensive operations to be performed.

#2 Improved User Experience

Users do not have to wait for time-consuming processes to finish. This leads to a more responsive and efficient application experience

#3 Scalability

Asynchronous processing is well-suited for handling large datasets and complex operations. It allows for better scalability as the application grows.

4 Use Case Features for Asynchronous Apex

These features are four different ways users can execute async processes according to different conditions or requirements. Whether scheduling tasks, handling extensive data, or making external callouts, you need to choose the appropriate feature based on your specific use case to build robust and efficient solutions in Salesforce.

  1. Future Methods
  2. Queueable Apex
  3. Batch Apex
  4. Scheduled Apex / Apex Scheduler

1. Future Methods

Future Methods are created using the @future annotation in Apex. Future methods allow you to run processes in a separate thread at a later time when system resources become available.

Key Points:

  • Mark a method with @future to make it a Future Method.
  • Future methods allow parallel execution without blocking the primary transaction.

Purpose:

  • To prevent delaying the current transaction.
  • To handle resource-intensive operations efficiently.

Common Scenarios:

  • Executing long-running methods.
  • Making callouts to external web services.
  • Segregating DML operations and bypassing the mixed save DML errors.

Example:

Invoking an external API to update inventory levels asynchronously.

@future (callout=true) public static void updateInventoryLevels(String productId) { ... }

Syntax:

global class FutureClass
{
@future
public static void myFutureMethod()
{
// Perform some operations
}
}

2. Queueable Apex

Queueable Apex allows you to queue up and execute long-running jobs asynchronously. It’s like putting a task in a line (queue) to be completed later.

Key Points:

  • Queueable Apex involves creating a public class that implements the Queueable interface and includes an execute method that accepts a QueueableContext parameter only.
  • You can start a Queueable job by calling System.enqueueJob() with an instance of the class.
  • It’s an advanced version of the Future method, offering extra features and more control over processes compared to future methods.
  • It is a chainable method.

Purpose:

  • To add, execute, and monitor jobs in a queue.

Common Scenarios:

  • Transferring complex types between jobs.
  • To chain multiple jobs together.
  • To start a long-running operation and get an ID for it.

Example:

Queue a job to migrate data from one system to another in the background, preventing timeouts during large data transfers.

@future (callout=true) public static void updateInventoryLevels(String productId) { ... }

Syntax:

public class SomeClass implements Queueable
{
public void execute(QueueableContext context)
{
// awesome code here
}
}

SomeClass sc = new SomeClass();
Id jobID = System.enqueueJob(sc);

3. Batch Apex

Batch class is a technique designed for processing large numbers of data records in chunks (small sections), handling more work than can be done in a single transaction.

Key Points:

  • Batch Apex involves writing an Apex class that implements the Salesforce-provided interface Database.Batchable, which allows for the processing of data in chunks.
  • The Database.Batchable interface requires the implementation of three methods:
    1. Start method – Identifies the scope (record/list) of the data to be processed.
    2. Execute method – Processes each batch of the scoped records.
    3. Finish method – Performs any post-job wrap-up tasks.

Purpose:

  • To efficiently handle large or complex datasets by breaking them into manageable batches.

Common Scenarios:

  • Performing database maintenance tasks.
  • Data transformation or migration.
  • Performing long-running jobs that require larger query results than a regular async transaction allows.

Example:

Analyzing (calculates statistics or generates reports) order history data in batches of 500 orders to avoid exceeding governor limits.

Database.executeBatch(new
ProcessLargeOrderHistory(orders), 500);

Governor limits for Asynchronous processes

3.1 Start method

  • Collects the records or objects to be processed.
  • Returns either a Database.QueryLocator object or an iterable containing the records or objects.

Syntax:

public (Database.QueryLocator | Iterable)
start(Database.BatchableContext bc) {}

3.2 Execute method

  • Processes each batch of records passed to it.
  • Takes a reference to the Database.BatchableContext object.
  • Batches of records execute in the order they were received from the start method. However, the order of execution isn’t guaranteed as it depends on various factors.

Syntax:

public void execute(Database.BatchableContext BC, list){}

3.3 Finish method

  • Performs post-processing operations after all batches are processed, e.g., sending confirmation emails.

Syntax:

public void finish(Database.BatchableContext BC){}

4. Scheduled Apex / Apex Scheduler

Scheduled Apex allows you to schedule an Apex class to run at specific times or intervals and automate tasks based on a fixed schedule.

Key Points:

  • Scheduled Apex involves creating a global class that implements the Schedulable interface and includes an execute method.
  • There are two options for scheduling classes –
    1. By System Scheduler.
    2. By Developer console.
    3. Finish method – Performs any post-job wrap-up tasks.
  • To schedule a class using the System Scheduler,
    • Step 1 – Go to Setup > Apex Class > search and click the “Schedule Apex” button.
    • Step 2 – Select the scheduler class and set the desired time for execution.
  • Alternatively, you can use the Developer Console:
    • Execute the following code snippet –
      AccountUpdateBatchJobscheduled m = new AccountUpdateBatchJobscheduled();
      String sch = '20 30 8 10 2 ?'; // Specify the schedule time
      String jobID = system.schedule('Merge Job', sch, m);

Purpose:

  • To efficiently handle large or complex datasets by breaking them into manageable batches.

Common Scenarios:

  • Running code periodically (i.e, daily or weekly basis).
  • Automating tasks based on a fixed schedule.

Example:

  • nightly data cleanup tasks.
  • Sending weekly email notifications.

Syntax:

global class AccountUpdateBatchJobscheduled implements Schedulable {
global void execute(SchedulableContext sc) {
// AccountUpdateBatchJob b = new AccountUpdateBatchJob();
// database.executebatch(b);
}
}

Also read :

thumbnail image-salesforce-einstein
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *