Asynchronous Code

ליאור נכתב על ידי ליאור לביא, עודכן בתאריך 27/10/2023

When we execute code in Apex, it can operate in one of two ways:

  1. Synchronously - the code runs immediately after we call it.
  2. Asynchronously - the code will run in the future in a separate thread, and the decision of when to run it is made by the server based on the availability of resources and the job's position in the execution queue.

In Salesforce, there are four main methods for running code asynchronously:

  1. Future methods.
  2. Queueable Apex.
  3. Batch processes.
  4. Scheduled Apex.

Asynchronous Code, What Is It Good For?

One of the prominent advantages of using asynchronous methods is the ability to run an asynchronous method in parallel while continuing to use the system, saving the waiting time for its completion. In the following diagram, you can see an example with three tasks with different processing times: the first task takes 4 hours, and the other two take 2 hours each. By turning the first task into an asynchronous one, we can run it in the background and continue working on tasks 2 and 3 without waiting for it, reducing the total execution time to four hours instead of eight. The times in the example are for illustration purposes only.

Asynchronous Code.png

When Do We Want to Use Asynchronous Code?

  1. When making external service calls - making an external service call can involve waiting for a response that may take several seconds. Running an asynchronous method for an external service call allows us to continue working without waiting for the response from the external service. Additionally, while waiting for the response from the external service, our connection to the database remains open, which is not acceptable in Salesforce.
  2. When a user makes changes to one record that result in changes to another record. In this case, we don't want the user to wait for the processing of the other record to finish. They should be able to continue working on the current record, and the changes to the other record can occur in the background.
  3. When we need to run a process that requires higher governor limits and we don't mind if the process doesn't execute immediately. Running code asynchronously in Salesforce allows for higher limits.
  4. When we need to process a very large number of records, even millions of records, with a background process.
  5. When we need to schedule a process to run at a specific time.
  6. When we need to open a separate thread to avoid a Mixed DML Operation error.