Asynchronous Apex Salesforce World Tour Paris 2015

32
Asynchronous Apex Paris June 25, 2015

Transcript of Asynchronous Apex Salesforce World Tour Paris 2015

Asynchronous Apex Paris June 25, 2015

Samuel De RyckeSalesforce MVP

ABSI @SamuelDeRycke

Samuel MoysonDeveloper

ABSI @SamuelMoyson

Speakers

#DevZone #SalesforceWorldTour #AsyncApex

Safe HarborSafe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.

Follow Developer Force for the Latest News

@SalesforceDevs – #SalesforceDevs

Developer Force – Force.com Community

+Developer Force – Force.com Community

Developer Force

Developer Force Group

Synchronous vs Asynchronous

• Synchronous

• Asynchronous

Process 1

Process 2

Waiting for response

Process 1

Process 2

Continues working

Get response

• Synchronous •Immediate and fast actions•Enforce single, serial, transactions•Normal governor limits

• Asynchronous •Actions that should not block the rest of the process•Processes where duration is of lesser concern•Higher governor limits

Synchronous vs Asynchronous

Types of Asynchronous Apex

• Batch Apex• Future Methods• Queueable• Scheduled• Continuation

Batch Apex

Use when you want to:• Process a big “batch” of records in smaller “batches” of

records• Each smaller batch is handled in a discrete transaction• Monitor queue of batch jobs• Batchable context with information about batch

Batch Apex

Start

Execute

Finish

global Database.QueryLocator start(Database.BatchableContext BC) {

//Query for data return Database.getQueryLocator(query);}

global void execute(Database.BatchableContext BC, List<sObject> scope) {

//Do some actions with data//DML Statement }

global void finish(Database.BatchableContext BC) {//Give some feedback about statistics of batch//Do post batch actions}

Batch Apex

Process up to 50 million recordsMonitor batch progress in the Setup User InterfaceAdmins can reorder batch priority with Apex Flex

Queue

Maximum 5 concurrent batches processed (status Queued)

Not always easy to debug

Future Methods

Use when you want to:• Execute methods that should not delay or respond to

the current Apex transaction• Isolate transaction contexts and DML contexts• Make asynchronous call outs to Web services

Pilot: Future methods with Higher Limits• Set specific governor limits for a specific method x2 or

x3

Future Methods

Executepublic class MyClass{

public void myNormalMethod{List<ID> recordIds;

//Synchronous logic heremyFutureMethod(recordIds);

// More synchronous logic }

@future public static void myFutureMethod(List<ID>

recordIds) { // Get those records based on the IDs // Process records }}

@future

Future Methods

Executed near instantlyBypass mixed DML limitations Pilot: increase limits for specific methods

Maximum 50 future methods per Apex invocation Only accepts (collections of) primitive data types

Future methods can not invoke other future methodsCan not be invoked from Visualforce Constructors, Get

& Set

Queueable Apex

Use when you want to:• Start long-running operations and monitor them within

the current process or the user interface• Pass complex types• Chain asynchronous jobs

Queueable Apex

implements

Queueable

ID jobID = System.enqueueJob(new MyQueueableJob ());

public class MyQueueableJob implements Queueable {

//Other logic

public void execute(QueueableContext context) {//Asynchronous logic here

//Optionally: enqueue another job }}

Queueable Apex

Executed near instantlyUnlimited depth of chained jobs (except for Dev & Trial

orgs)Use sObject and Apex objects as parameters

Maximum 50 jobs queued in a single apex transactionWhen chaining jobs only 1 ‘child job’ is supportedJobs can not be chained in test context.Chained jobs do not support callouts (Winter ‘16 ?)

Schedulable Apex

Use when you want to:• Schedule Apex classes• Specify schedule with User Interface or Apex

Schedulable Apex

// Schedulable classglobal class MySchedulable implements Schedulable {

global void execute(SchedulableContext sc) {

// Execute apex }

}

// Schedule from Apex: MySchedulable schApex = new MySchedulable ();String sch = '0 15 10 * * ?';String jobID = System.schedule('MySchedulable', sch, schApex);

implements

Schedulable

Schedulable Apex

Schedule from UI

Schedulable Apex

Execute Apex on scheduled intervalsAdmins can manage the schedule from the Setup UI

Maximum 100 scheduled jobs at the same time Using the Setup User Interface the minimum interval is 1 hour

Synchronous web service callouts are not supported

Continuation

Use when you want to:–Make callouts from Visualforce pages–Special one: synchronous asynchronous

Twitter demo

https://github.com/SamuelMoy/TwitterContinuationDemo

Continuation

Visualforce Continuation Webservice

startRequest

processResponse

Class● Objects● Methods

Continuation

// Visualforce page<apex:page showHeader="true" sidebar="true" controller="TwitterController">

<apex:form > <!-- Invokes the action method when the user clicks this

button. --><apex:commandButton action="{!startRequest}" value="Start" reRender="result"/> </apex:form>

<!-- This output text component displays the callout response body. --> <apex:outputText id="result" value="{!status} " />

</apex:page>

Visualforce

Continuation

// Action methodpublic Object startRequest() {

// Create continuation with a timeoutContinuation con = new Continuation(40);// Set callback methodcon.continuationMethod='processResponse'; HttpRequest req = new HttpRequest(); // Add callout request to continuationthis.requestLabel = con.addHttpRequest(req); // Return the continuationreturn con;

}

startRequest

Continuation

// Callback method public Object processResponse() {

// Get the response by using the unique label HttpResponse response =

Continuation.getResponse(this.requestLabel); // Set the result variable that is displayed on the

Visualforce page this.result = response.getBody();

// Return null to re-render the original Visualforce page return null;}

processResponse

Continuation

Integrate Visualforce with back-end systemsNo long-running concurrent request limit for call outs

that last longer than 5 seconds

Visualforce page suspended until action completed (= Synchronous)Maximum 3 asynchronous callouts in one single

ContinuationMaximum timeout continuation is 120 seconds

Testing Asynchronous Apex

• Invoke asynchronous Apex between the Test.startTest() and Test.stopTest() methods.

• The Test.stopTest() method will execute all asynchronous and scheduled Apex synchronously.

• Assert :-)

Recap

Batch Future Schedulable

Queueable Continuation

High volume of records

Near instantly

Primitive parameters

Schedule jobs

Chain jobs

Complex parameters

Callouts in Visualforce

Samuel De RyckeSalesforce MVP

ABSI@SamuelDeRycke

Samuel MoysonDeveloper

ABSI@SamuelMoyson

Q & A

developer.salesforce.com/trailhead

La communauté des développeurs Salesforce en France

Rejoignez la communauté de développeurs en France et venez partager votre

expérience sur la plateforme Salesforce1

bit.ly/dugParis

bit.ly/dugStQuentin

bit.ly/dugSuisse

bit.ly/dugBelgique

Thank you