Asynchronous Apex

Episode 7 – Asynchronous Processing in Apex

Writing business logic in Apex that runs for a long duration is often a key ask by customers. In this episode we will learn about writing asynchronous process in Apex using Apex. Join us as you embark on this wonderful journey to become a champion Salesforce developer.

Episode 7 will be presented by Jigar Shah on Feb 18, 2020 at 6 PM Indian Standard Time.

Agenda

  • Avenues of writing asynchronous processes
  • Batch Processing
  • Writing Scheduled Cron Jobs
  • Future Methods
  • Queueable
  • Q & A

Most importantly don’t break a leg if you are overwhelmed with the pace of the live sessions. All Apex Hours for Student sessions will be recorded and will be available on our YouTube channel.

Please register here and follow our ApexHours website to get more notification.

Here is some keynote from our session

Demystifying Asynchronous Processing

Demystifying Asynchronous Processing

Demystifying Asynchronous Processing

Understanding Batch Apex


Understanding Batch Apex

Anatomy of a Batch Job

Demo 1 – Batch Job

global class BatchDemo1 implements Database.Batchable<Sobject>{

	private Integer magicNum = 0;

	global Database.QueryLocator start(Database.BatchableContext bc){
		return Database.getQueryLocator('Select Id, Name From Account');
	}
	
	global void execute(Database.BatchableContext bc, List<Account> scope){
		System.debug('In the execute method');
        for(Integer i = 0; i < 5; i++){
        	magicNum = i; 
        }
	}

	global void finish(Database.BatchableContext bc){
		System.debug('In the finish method');
		System.debug('magicNum ' + magicNum);
	}
}

BatchDemo1 bd = new BatchDemo1();
Database.executeBatch(bd);

Maintaining State in Batches .

Maintaining State in Batche

Considerations for Batch Apex

  • 50 million records can be processed
  • Use Batch Apex when there are more than 1 batches to be processed else opt for Queueable Apex
  • Fine tune your SOQL query to minimize QueryLocator records
  • Invocation from Triggers may lead to uncontrolled executions
  • Implement Database.AllowsCallouts to make Webservice calls

Understanding Scheduled Apex

Understanding Scheduled Apex

Crone job

Considerations for Schedulers

  • Maximum 100 jobs can be scheduled concurrently
  • Limit on maximum number of Scheduled Apex invocations on a per 24 hour basis
  • Synchronous Web service callouts are not supported from Scheduled Apex

Future Calls

  • Asynchronous jobs running in a separate thread when resources are available
  • @future annotation
  • Primitive type support only
  • Applicability
    • Callouts to external applications or webservices
    • Perform complex calculations
    • Resolve and Mixed DML Operation error

Key Future Method Considerations

Must be static and do not return anything other than void
Order of invocation is not respected
Primitive type support only
Cannot invoke a future method from another future method

Queueable Apex

  • Asynchronous process that can be queued for sequential processing
  • System.Queueable
  • Supports Primitive & Non-Primitive types as well
  • Generally used for Job Chaining

Which async artefact to use?

Need Batch Apex Scheduled Apex Future Methods Queueable Apex
Process large data volumes Yes
Execute logic at specific time intervals Yes
Perform Web Service Calls Yes Yes Yes
Sequential Processing (Chaining) Yes
Support for Non-Primitive (sObject, custom Apex types) Yes Yes Yes

Recording

Asynchronous Apex using future method and Queueable Apex

Further Learning

  • Async Apex Basics

Assignment

Complete below assignment to win $1000 Salesforce Voucher. Click here for rule.

Write  a batch job that runs daily at 9 PM Local Time and searches for the newly created Accounts. The job then sums the Amount field value on every Opportunity for all the Opportunities and updates it on the respective Pipeline Amount field on the respective Parent Account record of those Opportunity.

(Hint: Assume Pipeline Amount field to be a custom currency field created on Account. Use a combination of Scheduled and Batch Jobs to achieve the desired functionality.)

Don’t forget to register for our next session on Integration in Salesforce. Check this post for all other session detail.

Please note that we have limit of 500 attendees that can join the online sessions. However, recording will be posted on our YouTube channel. Make sure to subscribe our YouTube channel to get notification for video upload.

So, learn at your pace and free will and ace your journey to Salesforce!

4,622 total views, 11 views today

11 thoughts on “Episode 7 – Asynchronous Processing in Apex”

  1. The chart at the end of the future and queuable apex video shows that you cannot make web service callouts from queuable apex but that does not seem correct based on what I have seen. Can you please confirm?

    Reply
    • Callout not allowed from this future method. You need to enable callout by annotating the future method. eg: @Future(callout=true)
      For Queueable: you need to implements Database.AllowsCallouts

      Reply
  2. Solution :

    STEP 1 – Class 1

    global class BatchAccountWithOpp implements Database.Batchable
    {
    global Database.QueryLocator start ( Database.BatchableContext bc ) {

    String query = ‘ SELECT Id, Name, Pipeline_Amount__c, ( SELECT ID, Amount FROM Opportunities ) FROM
    Account WHERE CreatedDate = LAST_N_DAYS:1 ‘;

    return Database.getQueryLocator ( query );

    }

    global void execute ( Database.BatchableContext bc, List scope ) {

    Decimal sum = 0;

    for( Account acc : scope ) {

    for ( Opportunity opp : acc.opportunities ) {

    sum = sum + opp.Amount ;

    }

    acc.Pipeline_Amount__c = sum;

    }

    update scope;
    }

    global void finish(Database.BatchableContext bc){
    system.debug(‘OutPut’);

    }

    }

    Step 2 – Class 2.

    global class BatchScheduleUpdate implements Schedulable
    {
    global void execute ( SchedulableContext sc ) {

    BatchAccountWithOpp ba = new BatchAccountWithOpp();
    database.executeBatch(ba, 200);
    }

    }

    Step 3 – Execute following code in Anonymous Window

    BatchScheduleUpdate batchSch = new BatchScheduleUpdate();

    String sch = ‘0 0 21 * * ?’;

    System.schedule ( ‘Batch Schedule’ , sch,batchSch ) ;

    Reply
  3. Code for Assignment Day 7
    ——————————–

    Step 1
    ——–

    global class BatchAmountUpdateOnAccount implements Database.Batchable {

    private Decimal totalAmount;
    private List listAccount = new List();
    DateTime twentyFourHoursAgo = System.now().addHours(-24);
    DateTime currentTime = System.now();
    global Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator(‘select Id,Pipeline_Amount__c,(select Id,amount from Opportunities) from Account where createdDate >= :twentyFourHoursAgo and createdDate <= :currentTime');
    }

    global void execute(Database.BatchableContext context, List accounts) {
    for(Account account : accounts) {
    totalAmount = 0.0;
    for(Opportunity opportunity : account.Opportunities) {
    totalAmount = totalAmount + opportunity.amount;
    }
    System.debug(‘Id:’ + account.Id + ‘ Total Amount:’ + totalAmount);
    account.Pipeline_Amount__c = totalAmount;
    listAccount.add(account);
    }
    update listAccount;
    }

    global void finish(Database.BatchableContext context){

    }
    }

    Step 2
    ———

    global class AmountUpdateOnAccountSchedular implements Schedulable {
    global void execute(SchedulableContext context) {
    BatchAmountUpdateOnAccount batchAccount = new BatchAmountUpdateOnAccount();
    Database.executeBatch(batchAccount,100);
    }
    }

    Step 3
    ———

    Goto Setting -> Setup -> Custom Code -> Apex Class
    Click on Schedule Apex button

    Job Name: Any Name
    Apex Class: AmountUpdateOnAccountSchedular
    Schedule Apex Execution: Select all days
    Start: Today
    End: Today + 365
    Preferred Start Time: 9:00 PM
    Save

    Reply

Leave a Comment