Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Salesforce asynchronous apex

4.018 Aufrufe

Veröffentlicht am

Salesforce asynchronous apex

  1. 1. What is synchronous & asynchronous? When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.
  2. 2. Simple code example private void example(){ System.debug("Before call"); doSomething(); System.debug("After call"); } private void doSomething(){ System.debug("In call"); } This will always output: Before call In call After call But if we were to make doSomething asynchronous (multiple ways to do it), then the output could become: Before call After call In call
  3. 3. Asynchronous Apex features and when to use each: Asynchronous Apex Feature When to Use Future Methods • When you have a long-running method and need to prevent delaying an Apex transaction • When you make callouts to external Web services • To segregate DML operations and bypass the mixed save DML error Queueable Apex • To start a long-running operation and get an ID for it • To pass complex types to a job • To chain jobs Batch Apex • For long-running jobs with large data volumes that need to be performed in batches, such as database maintenance jobs • For jobs that need larger query results than regular transactions allow Scheduled Apex • To schedule an Apex class to run on a specific schedule Continuations • Asynchronous Callouts to a SOAP or REST Web service from Visualforce Pages
  4. 4. New features in future method 1. Run Future Methods with Higher Limits. One of the following limits can be doubled or tripled for each future method. • Heap size • CPU timeout • Number of SOQL queries • Number of DML statements issued • Number of records that were processed as a result of DML operations, Aprroval.process, or Database.emptyRecycleBin. Ex: @future(limits='2x|3xlimitName'). 2. The execution limits of future methods and callouts in an Apex transaction have increased to 50 methods and 100 callouts respectively. Ex: 1. Trigger CreateGroupMember on Account. 2. Trigger Create community user on Account.
  5. 5. Queueable interface is new kid on the async block Take control of our asynchronous Apex processes by using the Queueable interface. This interface enables us to add jobs to the queue and monitor them, which is an enhanced way of running your asynchronous Apex code compared to using future methods. And here is list of limits from Queueable Apex vs Future methods: Queueable Future Methods The execution of a queued job counts once against the shared limit for asynchronous Apex method executions. Same You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. No more than 50 method calls per Apex invocation. The maximum stack depth for chained jobs is two, which means that you can have a maximum of two jobs in the chain. A future method can’t invoke another future method. When chaining jobs, you can add only one job from an executing job with System.enqueueJob. Methods with the future annotation cannot take sObjects or objects as arguments.
  6. 6. Queueable Example: 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()); 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. This example uses the jobID variable that was obtained in the previous example. AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
  7. 7. Queueable Example: Chaining Jobs If we need to run a job after some other processing is done first by another job, we 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. 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()); } } Note: We can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if Apex is running in test context by calling Test.isRunningTest() before chaining jobs. To better explain this, consider the following scenario. In a system, process 1 would update all the Accounts where Type picklist is empty to “Technology Partner”, and process 2 needs to look at all Accounts where Type picklist is “Technology Partner” and update all the related Opportunities for those Accounts where Stage picklist is empty to “Prospecting”. The process 2 needs to execute once the process 1 is completed only.
  8. 8. Batch Apex • Advantages 1. It can process up to 50m records 2. It can be scheduled to run at a particular time 3. Asynchronous processing • Disadvantages 1. Only 5 concurrent batch jobs running at a time 2. It’s difficult to troubleshoot 3. Execution may be delayed based on server availability 4. @future methods are not allowed 5. Can’t use getContent/getContentAsPDF methods 6. and a few more governor limits…
  9. 9. Holding Batch Jobs in the Apex Flex Queue With Apex Flex Queue, you can submit up to 100 batch jobs without getting an error. • The batch job is placed in the Apex flex queue, and its status is set to Holding. • If the Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and doesn’t add the job to the queue. Reordering Jobs in the Apex Flex Queue: While submitted jobs have a status of Holding, we can reorder them in the Salesforce user interface to control which batch jobs are processed first. To do so, from Setup, click Jobs | Apex Flex Queue. Still the system can process up to five queued or active jobs simultaneously for each organization.
  10. 10. Now we are here: Batchable @future Queueable - Good at processing large number of records (50m). - Can be scheduled to run at a certain time - Maximum of 5 concurrent jobs running at a time - You need good error handling for troubleshooting - Quick async processing (typically 1 record at a time) e.g. avoid mixed DML or a web service callout - Faster than a Batch - Easy to implement - Only accepts primitive type arguments - Can’t chain jobs - Hard to monitor - Quick async processing that supports primitive types - Faster than a batch - Ability to chain jobs - Can’t have more than 1 job doing callouts within the chain - Can be monitored
  11. 11. Continuation object in Apex - Asynchronous callouts for long running request We may run into scenario in Salesforce project, where we need call external web service but no need to wait for response. Response from external web service can be processed asynchronously and once processed it can be presented in Visualforce page. Execution Flow of an Asynchronous Callout We can accomplish this by using Actionsupport or Javascript remoting. However, this is possible with using Continuation method as well. In Continuation approach, we can call external web service and inform that which callback method should be used to process response. After execution of callback method, data is presented in visualforce page. Ex:-
  12. 12. Thank you