Queueable Apex Flashcards
What is the purpose/use of Queueable Apex?
- You can take control of your asynchronous Apex processes by using the
Queueable
interface. - The interface enables you to add jobs to the queue and monitor them.
- Using the interface is an enhanced way of running your asynchronous Apex code compared to using future methods.
What processes in Apex can be run asynchronously using Queueable
interface ?
- Apex processes that run for a long time, such as extensive database operations or external web service callouts, can be run asynchronously by implementing the
Queueable
interface and adding a job to the Apex job queue. - Your asynchronous apex job runs in the background in its own thread and doesn’t delay the execution of your main Apex logic.
- Each queued job runs when system resources become available. A benefit of using the
Queueable
interface methods is that some governor limits are higher than for synchronous Apex, such as heap size limits.
What benefits do Queueable jobs have over future methods ?
Queueable jobs have these additions benefits over future methods :
- Getting an ID for your job: When you submit your job by invoking the
System.enqueueJob
method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. Use this ID to identify and monitor your job either through the Salesforce UI (Apex Jobs page), or programmatically by querying your record from AsyncApexJob. - Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
- Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if your process depends on another process to have run first.
What is maximum stack depth of chained Queueable Jobs ?
You can set a maximum stack depth of chain Queueable jobs overriding the default limit of five in Developer and Trial Edition organizations.
What happens to variables declared as transient in Queueable Apex ?
Variables that are declared transient
are ignored by serialization and deserialization and the value is set to null in Queueable Apex.
Which method is used to add the queueable apex job to the apex queue ?
The System.enqueueJob(queueable)
method is used to add the job to the queue.
To add a queueable class as a job on the queue, call this method: ID JobID = System.enqueueJob(new AsyncExecutionExample());
Which method and interface must the Queueable Class implement ?
- The class must implement the Queueable interface and contain the
execute
method. - Method -
public void execute(QueueableContext context)
public class AsyncExecutionExample implements Queueable { public void execute(QueueableContext context) { Account a = new Account(Name='Acme',Phone='(415) 555-1212'); insert a; } }
How to monitor the status of a submitted queueable job ?
- You can monitor the status of your job programmatically by querying ApexAsyncJob or through the user interface in Setup by entering
Apex Jobs
in theQuick Find
box, then selectingApex Jobs
. - To query information about your submitted job, perform a SOQL query on AsyncApexJob by filtering on the job ID that the
System.enqueueJob
method returns.
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id =: jobID];
Do queueable jobs process batches ?
Similar to future jobs, queueable jobs don’t process batches, and so the number of processed batches and the number of total batches are always zero.
How to add Queueable Job with a Specified Minimum Delay ?
- Use the
System.enqueueJob(queueable,delay)
method to add queuable jobs to the asynchronous execution queue with a specified minimum delay (0 - 10 minutes). - The delay is ignored during Apex testing.
- When you set the delay to 0 (zero), the queueable job is run as quickly as possible. With chained queueable jobs, implement a mechanism to slow down or halt the job if necessary. Without such a fail-safe mechanism in place, you can rapidly reach the daily async Apex limit.
What are some situations in which adding a minimum delay would be advisable ?
It would be beneficial to adjust the timing before the queueable job is run
- If the external system is rate-limited and can be overloaded by chained queueable jobs that are making rapid callouts.
- When polling for results, and executing too fast can cause wasted usage of the daily async Apex limits.
Integer delayInMinutes = 5; ID jobID = System.enqueueJob(new MyQueueableClass(), delayInMinutes);
Setting a default org-wide delay for Queueable Jobs in the org ?
- Admins can define a default org-wide delay (1-600 seconds) in scheduling queueable jobs that were scheduled without a delay parameter.
- Use the delay setting as a mechanism to slow default queueable job execution.
- If the setting is omitted, Apex uses the standard queueable timing with no added delay.
- Using the
System.enqueueJob(queueable,delay)
method ignores any org-wide enqueue delay setting.
What are the ways to define org-wide delay for queueable jobs ?
- From Setup, in the Quick Find box, enter
Apex Settings
, and then enter a value (1-600 seconds) for Default minimum enqueue delay (in seconds) for queueable jobs that do not have a delay parameter. - To enable this feature programmatically with Metadata API see
ApexSettings
in theMetadata API Developer Guide
.
How to add a queueable job with a specified stack depth ?
- Use the
System.enqueueJob(queueable,asyncOptions)
method where you can specify the maximum stack depth and the minimum queue delay in the asyncOptions parameter. - The
System.AsyncInfo
class properties contain the current and maximum stack depths and the minimum queueable delay. - The
System.AsyncInfo
class has methods to help you determine if maximum stack depth is set in your Queueable request and to get the stack depths and queue delay for your queueables that are currently running.
These are the methods in the System.AsyncInfo
class
- hasMaxStackDepth()
- getCurrentQueueableStackDepth()
- getMinimumQueueableStackDepth()
- getMinimumQueueableDelayInMinutes()
Example of using stack depth to terminate a chained job and prevent it from reaching the daily maximum number of asynchronous Apex method executions ?
// Fibonacci public class FibonacciDepthQueueable implements Queueable { private long nMinus1, nMinus2; public static void calculateFibonacciTo(integer depth) { AsyncOptions asyncOptions = new AsyncOptions(); asyncOptions.MaximumQueueableStackDepth = depth; System.enqueueJob(new FibonacciDepthQueueable(null, null), asyncOptions); } private FibonacciDepthQueueable(long nMinus1param, long nMinus2param) { nMinus1 = nMinus1param; nMinus2 = nMinus2param; } public void execute(QueueableContext context) { integer depth = AsyncInfo.getCurrentQueueableStackDepth(); // Calculate step long fibonacciSequenceStep; switch on (depth) { when 1, 2 { fibonacciSequenceStep = 1; } when else { fibonacciSequenceStep = nMinus1 + nMinus2; } } System.debug('depth: ' + depth + ' fibonacciSequenceStep: ' + fibonacciSequenceStep); if(System.AsyncInfo.hasMaxStackDepth() && AsyncInfo.getCurrentQueueableStackDepth() >= AsyncInfo.getMaximumQueueableStackDepth()) { // Reached maximum stack depth Fibonacci\_\_c result = new Fibonacci\_\_c( Depth\_\_c = depth, Result = fibonacciSequenceStep ); insert result; } else { System.enqueueJob(new FibonacciDepthQueueable(fibonacciSequenceStep, nMinus1)); } } }
How to test queueable jobs ?
A queueable job is an asynchronous process.
To ensure that this process runs within the test method, the job is submitted to the queue between the Test.startTest
and Test.stopTest
block.
The system executes all asynchronous processes started in a test method synchronously after the Test.stopTest
method.
@isTest public class AsyncExecutionExampleTest { @isTest static void test1() { // startTest/stopTest block to force async processes // to run in the test. Test.startTest(); System.enqueueJob(new AsyncExecutionExample()); Test.stopTest(); // Validate that the job has run // by verifying that the record was created. // This query returns only the account created in test context by the // Queueable class method. Account acct = [SELECT Name,Phone FROM Account WHERE Name='Acme' LIMIT 1]; System.assertNotEquals(null, acct); System.assertEquals('(415) 555-1212', acct.Phone); } }
How to chain queueable jobs ?
- To run a job after some other processing is done first by another job, you can chain queueable jobs.
- To chain a job to another job, submit the second job from the
execute()
method of your queueable class. - You can add only one job from an executing job, which means that only one child job can exist for each parent job.
public class AsyncExecutionExample implements Queueable { public void execute(QueueableContext context) { // Your processing logic here // Chain this job to next job by submitting the next job System.enqueueJob(new SecondJob()); } }
How to allow HTTP and web service callouts from queueable jobs ?
- Apex allows HTTP and web service callouts from queueable jobs, if they implement the
Database.AllowsCallouts
marker interface. - In queueable jobs that implement this interface, callouts are also allowed in chained queueable jobs.
What are some queueable apex limits ?
- The execution of a queued job counts one time against the shared limit for asynchronous Apex method executions.
- You can add up to 50 jobs to the queue with
System.enqueueJob
in a single transaction. - In asynchronous transactions, you can add one job to the queue with
System.enqueueJob
. - To check how many queueable jobs have been added in one transaction, call
Limits.getQueueableJobs()
. - Because no limit is enforced on the depth of chained jobs, you can chain one job to another. You can repeat this process with each new child job to link it to a new child job.
- For Developer Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times. The maximum number of jobs in the chain is 5, including the initial parent queueable job.
- When chaining jobs with
System.enqueueJob
, you can add only one job from an executing job. Only one child job can exist for each parent qeueuable job. Starting multiple child jobs from the same queueable job isn’t supported.
What is the Transaction Finalizers feature ?
- The Transaction Finalizers feature enables you to attach actions, using the
System.Finalizer
interface, to asynchronous Apex jobs that use the Queueable framework. - A specific use case is to design recovery actions when a Queueable job fails.
- The Transaction Finalizers feature provides a direct way for you to specify actions to be taken when asynchronous jobs succeed or fail.
Before Transaction Finalizers what were the only two ways for asynchronous job failures ?
- Poll the status of
AsyncApexJob
using a SOQL query and re-enqueue the job if it fails. - FIre
BatchApexErrorEvents
when a batch Apex method encounters an unhandled exception.
What is the main purpose of Transaction Finalizers ?
With transaction finalizers, you can attach a post action sequence to a Queueable Job take relevant actions based on the job execution result.
How many times can a queueable job that failed due to an unhandled exception be re-enqueued ?
- A Queueable job that failed due to an unhandled exception can be successively re-enqueued five times by a transaction finalizer.
- This limit applies to a series of consecutive Queueable job failures.
- The counter is reset when the Queueable job completes without an unhandled exception.
Can a finalizers be implemented as inner classes ?
- Finalizers can be implemented as inner classes.
- You can implement both Queueable and Finalizer interfaces with the same class.