Showing posts with label Queueable. Show all posts
Showing posts with label Queueable. Show all posts

Tuesday, June 26, 2018

Asynchronous Apex: Using Queueable Apex


Queueable jobs are similar to future methods, but they provide you with these additional benefits.
  • 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. You can use this ID to identify your job and monitor its progress.
  • Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types.
  • Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some processing that depends on another process to have run first.
public class AsyncExecutionExample implements Queueable {
    public void execute(QueueableContext context) {
        Account a = new Account(Name='Acme',Phone='(415) 555-1212');
        insert a;        
    }
}

To add this class as a job on the queue, call this method:
ID jobID = System.enqueueJob(new AsyncExecutionExample());

Chaining 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. You can refer the code below for chaining jobs:

...
...
...
for (Case caseRecord : cases)
 caseRecord.Status = 'Closed';

for (Lead lead : leads)
 lead.Status = 'Inactive';

Map<Integer, List<sObject>> indexToObjects = new Map<Integer, List<SObject>>();
indexToObjects.put(0, cases);
indexToObjects.put(1, leads);

Integer startingIndex = 0;
System.enqueueJob(new Worker(indexToObjects, startingIndex));

Worker.cls
public without sharing class Worker implements Queueable {
 Map<Integer, List<sObject>> indexToObjectUpdates;
 Integer index;

 public Worker(Map<Integer, List<sObject>> indexToObjectUpdates, Integer index) {
  this.indexToObjectUpdates = indexToObjectUpdates;
  this.index = index;
 }

 public void execute(QueueableContext context) {
  if (!indexToObjectUpdates.containsKey(index))
   return;

  update indexToObjectUpdates.get(index);

  Integer nextIndex = index + 1;
  if (indexToObjectUpdates.containsKey(nextIndex))
   System.enqueueJob(new Worker(indexToObjectUpdates, nextIndex));
 }
}

Points to remember:
  • Apex allows HTTP and web service callouts from queueable and chained queueable jobs, if they implement the Database.AllowsCallouts marker interface.
  • You can monitor the status of your job programmatically by querying AsyncApexJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, then selecting Apex Jobs.
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top