Reader small image

You're reading from  Mastering Apex Programming

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781800200920
Edition1st Edition
Languages
Right arrow
Author (1)
Paul Battisson
Paul Battisson
author image
Paul Battisson

Paul Battisson is the CEO of Groundwork Apps, a Salesforce ISV Partner, a 9- time Salesforce MVP, and a current MVP Hall of Fame member. He has spoken at numerous Salesforce events including Dreamforce, London's Calling, the Salesforce London World Tour, India Dreamin, and DreamOle. He runs the Leeds Developer Group in the UK and the CloudBites TV website and YouTube channel where he helps Salesforce developers, consultants, admins and architects. He is the author of multiple books and training courses on Salesforce programming.
Read more about Paul Battisson

Right arrow

Chapter 9: Working with Queueable Apex

So far in this section on asynchronous processing in Apex, we have dealt with both future methods and Batch Apex, two different ways of processing data asynchronously with different use cases and benefits. In this chapter, we are going to discuss another asynchronous processing option that is somewhat of a hybrid of both—Queueable Apex.

We will discuss what Queueable Apex is and how it compares to both Batch Apex and future methods. This will help us to then define and understand use cases for Queueable Apex before we see how we define a Queueable Apex implementation. After defining a Queueable Apex implementation, we will see how to invoke a queueable job and how to chain jobs. We'll then finish the chapter by reviewing how we test our Queueable Apex classes.

In this chapter, we'll cover the following topics:

  • What Queueable Apex is
  • When to use Queueable Apex
  • Defining Queueable Apex implementations
  • Invoking...

What is Queueable Apex?

Queueable Apex was first introduced in the Winter '15 Salesforce release, that was some time around the end of 2014. It was delivered as a response to the growing use of both Batch Apex and future methods and developers finding use cases where neither was an ideal solution. This led to the development of Queueable Apex. Queueable Apex allows a developer to submit a job for processing and then at the end of that job, start another job, chaining multiple jobs together, something like this:

Figure 9.1 – Jobs are chained together with each job

From Figure 9.1, we see that each chained job is invoking another job, in the process, if needed until the full process is complete. Perhaps the best way to understand Queueable Apex is to understand the original reason it was designed. In his detailed blog post (https://developer.salesforce.com/blogs/engineering/2014/10/new-apex-queueable-interface.html), Josh Kaplan from the Salesforce...

When to use Queueable Apex

There are three primary use cases for Queueable Apex, which we will discuss in this section, however, you may notice that some of them overlap with use cases we previously discussed for future methods and Batch Apex. This is because there is typically no one right answer for how you should look to architect and develop a solution—although there are often many wrong ways of doing things. When working on some of these overlapping use cases, the key question to consider is whether you wish to chain the asynchronous process you are building. If the answer is yes, then you are almost always going to get the best results using a Queueable Apex implementation. Let's now look at some common use cases in the following sections.

Extensive or complex processes

The first key use case is for extensive or complex database processes. What do I mean by this? As we know, Salesforce has a series of governor limits that are in place to ensure that resources...

Defining Queueable Apex implementations

Queueable Apex, like Batch Apex, is defined through the implementation of an Apex interface, in this case, the Queueable interface.

To define a Queueable Apex job, we simply implement this interface, which has a single method, execute(QueueableContext context). A very basic implementation would then be the following:

public class ExampleQueueable implements Queueable {
	public void execute(QueueableContext context) {
		//Do something
	}
}

As we discussed, unlike our Batch Apex implementations, we must define the scope for the Queueable Apex job to process. We can do this in two ways. We can do it through the use of a query within our execute method:

public class ExampleQueueable implements Queueable {
    public void execute(QueueableContext context) {
          List<Account> accs = [SELECT Id, Name FROM Account        ...

Invoking Queueable Apex

Queueable Apex jobs are invoked using the System.enqueueJob method as shown in the following code snippet:

Id apexJobId = System.enqueueJob(new ExampleQueueable());

As is shown, the System.enqueueJob method returns an Id for an AsyncApexJob sObject instance that we can use to monitor the status of the Queueable Apex job in the same way we monitor the job in a Batch Apex context. It should be noted, however, that as Queueable Apex does not process batches of records, JobItemsProcessed and TotalJobItems will always return 0.

From a synchronous Apex process, we can enqueue 50 jobs but can only enqueue a single job when enqueuing from a Batch Apex or Queueable Apex class (more on this in the next section). There are some shared ways of circumventing this that can be found on the internet, such as scheduling another Apex job that will enqueue the job should you be at the limit of the available jobs in the queue. I would not recommend this for a number of...

Testing Queueable Apex

To test Queueable Apex, we follow the same pattern we have used for all our asynchronous code. We place the System.enqueueJob call between a Test.startTest method call and a Test.stopTest method call to run the asynchronous process synchronously:

@isTest
private class ExampleQueueable_Test {
	
	@isTest
	private static void testExecute() {
		Test.startTest();
		System.enqueueJob(new ExampleQueueable());
		Test.stopTest();
		//Assert on expected changes
	}
}

Note that if you were to run the following code:

@isTest
private class ExampleQueueable_Test {
	
    @isTest
    private static void testExecute() {
          Test.startTest();
          Id apexJobId = System.enqueueJob(new           ExampleQueueable());
          ...

Summary

In this chapter, we have looked at how we can use Queueable Apex as a way of allowing us to perform long-running or chained processes efficiently. As we have seen, Queueable Apex is a hybrid of future methods and Batch Apex, allowing developers to build out solutions that can execute efficiently and chain processes together where required.

We started the chapter by seeing how Queueable Apex compares to both future methods and Batch Apex, including discussing the historical context behind the tool being introduced. We then looked at specific use cases that are well suited to Queueable Apex, namely those where we may want to chain multiple items together. We also discussed how we can think about separating out our existing processes into a format that will work well in a queueable context and avoid governor limits.

We then saw how we define and invoke Queueable Apex classes and how to chain jobs together. Finally, we discussed some of the nuances of testing Queueable Apex...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Apex Programming
Published in: Nov 2020Publisher: PacktISBN-13: 9781800200920
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Paul Battisson

Paul Battisson is the CEO of Groundwork Apps, a Salesforce ISV Partner, a 9- time Salesforce MVP, and a current MVP Hall of Fame member. He has spoken at numerous Salesforce events including Dreamforce, London's Calling, the Salesforce London World Tour, India Dreamin, and DreamOle. He runs the Leeds Developer Group in the UK and the CloudBites TV website and YouTube channel where he helps Salesforce developers, consultants, admins and architects. He is the author of multiple books and training courses on Salesforce programming.
Read more about Paul Battisson