Queueable Apex Flashcards

1
Q

What is the purpose/use of Queueable Apex?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What processes in Apex can be run asynchronously using Queueable interface ?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What benefits do Queueable jobs have over future methods ?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is maximum stack depth of chained Queueable Jobs ?

A

You can set a maximum stack depth of chain Queueable jobs overriding the default limit of five in Developer and Trial Edition organizations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens to variables declared as transient in Queueable Apex ?

A

Variables that are declared transient are ignored by serialization and deserialization and the value is set to null in Queueable Apex.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which method is used to add the queueable apex job to the apex queue ?

A

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());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which method and interface must the Queueable Class implement ?

A
  • The class must implement the Queueable interface and contain the executemethod.
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to monitor the status of a submitted queueable job ?

A
  • You can monitor the status of your job programmatically by querying ApexAsyncJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, then selecting Apex 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];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Do queueable jobs process batches ?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to add Queueable Job with a Specified Minimum Delay ?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are some situations in which adding a minimum delay would be advisable ?

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Setting a default org-wide delay for Queueable Jobs in the org ?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the ways to define org-wide delay for queueable jobs ?

A
  • 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 the Metadata API Developer Guide.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to add a queueable job with a specified stack depth ?

A
  • 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()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Example of using stack depth to terminate a chained job and prevent it from reaching the daily maximum number of asynchronous Apex method executions ?

A
// 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to test queueable jobs ?

A

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);
    }
}
17
Q

How to chain queueable jobs ?

A
  • 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());
    }
}
18
Q

How to allow HTTP and web service callouts from queueable jobs ?

A
  • 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.
19
Q

What are some queueable apex limits ?

A
  • 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.
20
Q

What is the Transaction Finalizers feature ?

A
  • 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.
21
Q

Before Transaction Finalizers what were the only two ways for asynchronous job failures ?

A
  • 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.
22
Q

What is the main purpose of Transaction Finalizers ?

A

With transaction finalizers, you can attach a post action sequence to a Queueable Job take relevant actions based on the job execution result.

23
Q

How many times can a queueable job that failed due to an unhandled exception be re-enqueued ?

A
  • 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.
24
Q

Can a finalizers be implemented as inner classes ?

A
  • Finalizers can be implemented as inner classes.
  • You can implement both Queueable and Finalizer interfaces with the same class.
25
Q

Do the queueable job and finalizer run in separate apex and database transactions ?

A

The Queueable Job and Finalizer run in separate apex and database transactions.

For example, the Queueable can include DML and the Finalizer can include REST callouts. Using a Finalizer doesn’t count as an extra execution against your daily Async Apex limit.

26
Q

Which governor limits apply to a Finalizer transaction ?

A

Synchronous governor limits apply for the Finalizer transaction, except in these cases where asynchronous limits apply :
* Total heap size
* Maximum number of Apex jobs added to the queue with System.enqueueJob
* Maximum number of methods with the future annotation allowed per Apex invocation.

27
Q

What method must be implemented in System.Finalizer interface ?

A

The System.Finalizer interface includes the execute method.

global void execute(System.FinalizerContext ctx){}
  • This method is called on the provided FinalizerContext instance for every enqueued job with a finalizer attached.
  • Within the execute method, you can define the actions to be taken at the end of the Queueable job
  • An instance of System.FinalizerContext is injected by the Apex runtime engine as an argument to the execute method.
28
Q

What methods does the System.FinalizerContext interface contain ?

A

The System.FinalizerContext interface contains four methods :

  • getAsyncApexJobId method
global Id getAsyncApexJobId {}

Returns the ID of the Queueable job for which this finalizer is defined.

  • getRequestId method
global String getRequestId {}

Returns the request ID, a string that uniquely identifies the request, and can be correlated with Event Monitoring logs. To correlated with the AsyncApexJob table, use the getAsyncApexJobId method instead. The Queueable job and the Finalizer execution both share the (same) request ID.

  • getResult method
global System.ParentJobResult getResult {}

Returns the System.ParentJobResult enum, which represents the result of the parent asynchronous Apex Queueable job to which the finalizer is attached.
The enum takes these values : SUCCESS,UNHANDLED_EXCEPTION.

  • getException method
global System.Exception getException {}

Returns the exception with which the Queueable job failed when getResult is UNHANDLED_EXCEPTION, null otherwise.

29
Q

How to attach the finalizer to your Queueable jobs using System.attachFinalizer method ?

A

Attach the finalizer to your Queueable jobs using the System.attachFinalizer method :

  • Define a class that implements the System.Finalizer interface.
  • Attach a finalizer within a Queueable job’s execute method. To attach the finalizer, using as argument the instantiated class that implements the System.Finalizer interface.
global void attachFinalizer(Finalizer finalizer){}
30
Q

What are some additional implementation details regarding Finalizers ?

A
  • Only one finalizer instance can be attached to any Queueable job.
  • You can enqueue a single asynchronous Apex job (Queueable, Future, or Batch) in the finalizer’s implementation of the execute method.
  • Callouts are allowed in finalizer implementations.
  • The Finalizer framework uses the state of the Finalizer object (if attached) at the end of Queueable execution. Mutation of the Finalizer state, after it’s attached, is therefore supported.
  • Variables that are declared transient are ignored by serialization and de-serialization and therefore don’t persist in the Transaction Finalizer.
31
Q

Explain the various Transaction Finalizers Error Messages and their reason for failure ?

A
  1. Error Message
    More than one Finalizer cannot be attached to same Async Apex Job.

Failed Context
Queueable Execution

Reason for Failure
System.attachFinalizer() is invoked more than once in the same Queueable instance.

  1. Error Message
    Class {0} must implement the Finalizer interface.

Failed Context
Qeueuable Execution

Reason for Failure
The instantiated class parameter to System.attachFinazlier() doesn’t implement the System.Finalizer interface.

  1. Error Message
    Sytem..attachFinalizer(Finalizer) is not allowed in this context

Failed Context
Non-Queueable Execution

Reason for Failure
System.attachFinalizer() is invoked in an Apex context that’s not executing a Queueable instance.

  1. Error Message
    Invalid number of parameters

Failed Context
Queueable Execution

Reason for Failure
Invalid number of parameters to System.attachFinalizer()

5.Error Message
Argument cannot be null

Failed Context
Qeueuable Execution

Reason for Failure
System.attachFinalizer() is invoked with a null parameter

If you have a Splunk Add-On for Salesforce, you can analyze error messages in your Splunk log. Error messages in the Splunk Log.

  1. Error Message
    Error processing finalizer for queueable job id: {0}

Reason for Failure
Runtime error while executing Finalizer. This error can be an unhandled catchable exception or uncatchable exception (such as a LimitException). or less commonly, an internal system error.

  1. Error Message
    Error processing the finalizer (class name: {0}) for the queueable job id: {1} (queueable class id: {2})

Reason for failure
Runtime error while executing Finalizer. This error can be an unhandled catchable exception or uncatchable exception (such as a LimitException), or ,less commonly, an internal system error.