Skip to main content

What you'd like to know about Asynchronous Apex

About Us
Published by admin
23 September 2020
585

Hi there! Anyone who dealt with Salesforce governor limits knew how much it can complicate the developer's life. So, what should you do when you want to process a huge amount of data together? How to utilize resources to their best? Here comes Asynchronous Apex into the picture. It is typically used for callouts to external systems, operations that require higher limits, and code that needs to run at a certain time. In other words, you do not have to wait until process A completes to run the process D.

Today we are going to explore the difference between several asynchronous Apex features.

Generally there are 4 main features: Future, Queueable, Batch, and Scheduler. 

Asynchronous-Apex-1

Let's dive into the use cases of each feature. It enables us to make an informed decision when choosing one or another feature to address business goals correctly.

1. The Future Apex feature is used:

  • If you have a long-running operation and you need to prevent Apex transaction latency;
  • When you make callouts to external web services; 
  • To separate DML operations and work around mixed save errors.

Be aware that methods with the future annotation should be static and can only return void type. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with future annotation cannot accept sObjects or objects as arguments. There is a limit of 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24-hour period. 

Let's take a look at a sample code of the future method.

Asynchronous-Apex-2

 

2. Queueable Apex is used: 

  • To start a long operation and get an identifier for it (Job ID);
  • For transferring complex data types(SObject, List, Set, Map, Enum, and other);
  • If you need to link one task with another.

Queueable Apex is an asynchronous Apex process that implements a Queueable interface. The queueable interface contains only 1 method 'execute'. Queueable jobs are similar to the future method since both of them are queued and executed only after resources are available. Queueable Apex allows also non-primitive types. The following code is Queueable interface implementation and the creation of a new account.

Asynchronous-Apex-3

 

3. Batch Apex is used in the following cases: 

  • To long-running jobs with large amounts of data that need to be run in batches, there are tasks for maintaining the database;
  • To jobs that require larger query results than normal transactions allow.

Batch Apex implements a Batchable interface. This interface contains 3 methods such as ‘start’, ‘execute’, ‘finish’.

The 'Start' method can return either a Database.QueryLocator or Iterable<sObject> and it is called once at the beginning of a Batch Apex Job.

The 'Execute' method gets data from the 'start' method. The default size of this data is 200 chunks. 

The 'Finish' method executes post-processing operations (for example, sending an email) and is called once after all batches are processed. 

Also in Batch Apex, you can use ‘Database. AllowCallouts’. It enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending an HTTP request from Apex code and then receiving the response. If you specify Database. Stateful in the class definition, you can maintain state across these transactions. When using Database. Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions. 


Governor limits for Batch Apex:

  • Till 5 batch jobs can be queued or active concurrently;
  • Till 100 Holding batch jobs can be held in the Apex flex queue;
  • In a running test, you can submit a maximum of 5 batch jobs;
  • In a running test, you can submit a maximum of 5 batch jobs.

Asynchronous-Apex-4

 

4. Scheduler Apex is used: 

  • To schedule a class to run on a specific schedule.

This is ideal for daily or weekly maintenance tasks using Batch Apex. The following example implements the Schedulable interface for a class named testClass.

Asynchronous-Apex-5

 

This example uses the System. Schedule method to implement the above class. The ‘sch’ string contains a CRON expression. CRON expression is a string of subexpressions (fields) that describe individual schedule details. In salesforce, this expression has the following syntax: 'Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year'

Asynchronous-Apex-6

 

Some more examples of the usage of the CRON expression.

Asynchronous-Apex-7

 

Also, you can schedule a class from UI. This is very useful for non-developer users. To do this go to Setup - Apex Class and Select ‘Schedule Apex’.

Asynchronous-Apex-8

 

To schedule a weekly interval.

Asynchronous-Apex-9

 

To schedule a monthly interval.

Asynchronous-Apex-10

 

There is one more very interesting thing. You can run the Apex job every 1 hour using the default CRON expression, but what if we want it to run every 5 minutes?

The simplest solution you can find on the internet is to create 12 Apex jobs. But sometimes this is not what we want or need the client and it doesn't look very good.

Asynchronous-Apex-11

 

How to make it easier, without copy-paste and 12 Apex jobs?

This is quite an interesting task, try to do it yourself. For example, I will share one of my solutions.

Asynchronous-Apex-12

 

In conclusion, we would like to draw your attention to the testing of the Asynchronous Apex. Not to exceed the Salesforce limits use Test.startTest () and Test.stopTest () in Test methods during the testing process. Calling method(s) between Test.startTest and Test.stopTest ensure that any asynchronous transactions finish executing before Test.stopTest() exits. Asynchronous Apex works, any asynchronous code — a future method is a useful example — will not run as part of the Apex unit test unless we take certain actions. A unit test generates a single transaction, and asynchronous code placed in this transaction cannot be executed until the transaction completes successfully.

 

We hope this writing was pretty useful to you and helped you structure the knowledge about Asynchronous Apex features.

In case you'd like to get more insights on how to build an efficient Salesforce solution, get in touch and we’ll provide you with the necessary information.

 


Leonid Klimovich
Senior Project Manager

We have available resources to start working on your project within 5 business days

1 UX Designer

1 Admin

2 QA engineers

1 Consultant