Today's Offer - Salesforce Certification Training - Enroll at Flat 10% Off.

- Salesforce Blogs -

What is Asynchronous in Salesforce?

What is Asynchronous Job?

In an Asynchronous call, the thread will not wait until it completes its tasks before proceeding to next. Instead it proceeds to next leaving it runs in separate thread. In an Asynchronous call, the code runs in multiple threads which helps to do many tasks as background jobs Apex offers multiple ways for running your Apex code asynchronously. Choose the asynchronous Apex feature that best suits your needs. In an Asynchronous call, the code runs in multiple threads which help to do many tasks as background jobs. 

Example: Types of Asynchronous Job

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

Future Methods

A future methods executes when it has resources  available.A future method runs in the background, asynchronously. It is used for executing long-running operations like Web services, call outs or any other operation which has to run on its own time. If Future Annotation is not used in a web service call out, the thread will wait until the response comes and other processes will not be executed. Future methods are used to avoid to the mixed DML error. It is queued and executes when resources available to. So it doesn’t have to wait for the completion of a long-running operation. A future method increases the governor limits, such as SOQL query limits and heap size limits. It is define by @future annotation.

@Future:

Future annotation is used to execute methods asynchronously. When you define @Future, it executes when Salesforce has available resources.

Read: Difference Between Microsoft Dynamics and Salesforce CRM.

@Future (callout = true)

Specify the method to make the callout to external systems. (E.g. To execute callout method via an Apex trigger) salesforce Curriculum Note: 

  • Methods with the future annotation must be static methods and can only return a void type.
  • Future method parameters must be collections of primitive data types, primitive data types or arrays of primitive data types.
  • Methods with the future annotation cannot take Objects or objects as arguments.

Things to Remember

  • A future annotation must be static methods and return type is only void type.
  • In future method parameter must be collections of primitive data types, primitive data types or arrays of primitive data types it can’t take objects as arguments.
  • It is not necessary that future methods execute in the same order they were called. There is possible of that two future methods could run concurrently, which could result in record locking if the two methods were updating the same record.
  • It can’t be used in Visualforce controllers insetMethodName(), getMethodName() nor in the constructor.
  • Neither a future method cannot call from one future method to anther future method or it can  invoke a trigger that calls a future method while running a future method
  • The getContent() and getContentAsPDF() methods can’t be used in methods with the future annotation.
  • It limited to 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24-hour period.

Example


public class DemoFuture {
public void insertData(){
DemoFuture.ExampleMethod();
        Account acc=new Account(Name='Testing Record',industry='Energy',type='Other',phone='+22-3535543');
insertacc;
system.debug(acc);
    }
   @future
	public static void ExampleMethod (){
	profile p=[select id,name FROM profile WHERE name='Standard Platform User'];
		user u =newuser(alias='Gorge',email='[email protected]',
emailencodingkey='UTF-8',lastname='Samuel',languagelocalekey='en_US',
localesidkey='en_US',profileid=p.id, timezonesidkey='America/Los_Angeles',
userName='[email protected]',communityNickName='akash',isactive=false);

insert u;
system.debug(u);

 }
}

A user inserted What is Asynchronous in Salesforce Record Insert What is Asynchronous in Salesforce

Read: What is Salesforce? The Intriguing World of Salesforce.

What is batch apex?

Batch Apex is asynchronous Job. Batch apex allow to define a single job can be broken in to smaller parts, where every record can be processed separately. It processed the large number of records and more flexible in governor limits than the synchronous code. When a batch class invoke, the job is placed on the Apex job queue and is executed as a separate transaction. When to use Batch Apex?

  • When you want to process large number of records on daily basis or even on specific time of interval then you could go for Batch Apex.
  • Batch Apex is uses an interface that must be implemented by the developer. It can be programmatically invoked at runtime. Batch Apex divided total records in to small batches of records and processing down to manageable chunks of data.
  • It is used to build complex DML operations for bulk records processes that run on millions  of records on the Force.com platform

Syntax: Developer need define Database.Batchable Interface


Global class BatchExample implements Database.Batchable<sObject>{
}

Batch Apex Governor Limits

These are the governor Limits you need to keep in mind when dealing with Batch Apex

  • Up to five queued or active batch jobs are allowed for Apex.
  • Using Database.QueryLocator batch apex returns 50 million records if more than 50 million records are returned.
  • The batch apex Database.execute method can have batches of a maximum number of 2,000, minimum 1 and by default 200 batches.
  • Salesforce chunks the records returned by the start method and then passes each batch to the execute method where governor limits are reset for each execution of execute.
  • The batch apex can implement up to 10 callouts per each batch methods.
  • 250,000 is the maximum number of batch executions per 24 hours.
  • Only one batch Apex job's start method can run at a time in an organization. The batch jobs which haven’t started yet remain in the queue until they are started.

salesforce quiz Methods in Batch Apex There are three methods in batch apex.

  • Start method
  • Execute method
  • Finish method

Start method

This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating. Note the following points:

Read: How Can I Start my Career in the Salesforce Industry?
  • Using the Database.QueryLocator object it increases the query limit up to 50 million.
  • Use iterable object when you have complex criteria to process the records..

Syntax


globalDatabase.QueryLocator start(Database.BatchableContext b){

returnDatabase.getQueryLocator('select id, name from account );

}

Execute Method:

The record which returned from start methods are execute in to small chunks. Now every batch are separately runs the execute method.


Global void Execute (Database.BatchableContextb,list&lt;sObject&gt;acc){

}

Finish Method

This method gets called at the end and you could do some finishing activities like sending an email, call another batch job.Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back. Syntax


Global void finish(Database.BatchableContext b){

}

Example


global class batchExample  implements Database.Batchable&lt;sobject&gt;{

globalDatabase.QueryLocator start(Database.BatchableContext b){

returnDatabase.getQueryLocator('select id, name from account where name=\'United\'');

}

Global void Execute (Database.BatchableContextb,list&lt;account&gt;acc){

user u=[select id  from user where alias='peter'];

for(account a:acc){

if(a.industry=='Consulting'){

a.industry='Education';

a.OwnerId=u.id;

}

}

updateacc;

}

Global void finish(Database.BatchableContext b){

messaging.SingleEmailMessage email1= new messaging.SingleEmailMessage();

string [] toAdd= new string[]{'[email protected]'};

string [] toBcc= new string[]{'[email protected]'};

email1.setToAddresses(toadd);

// email1.setToAddresses(toBcc);

email1.SetSubject('work is completed');

email1.SetSenderDisplayName('JnabaskTraing');

email1.setPlainTextBody('batch apex process is completed');

messaging.Email[]email=  new messaging.Email[]{email1};

messaging.sendEmail(email);

}

}

batchExample  SS = new batchExample();

Database.executeBatch(SS, 5);

system.debug(ss);

What is Asynchronous in Salesforce Email response What is Asynchronous in Salesforce

Read: Salesforce Developer Salary in the USA- Things You Need to Know

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

9 days 14 Dec 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

-0 day 05 Dec 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

-0 day 05 Dec 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

1 day 06 Dec 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

15 days 20 Dec 2019

Course for testing

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

19 days 24 Dec 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

4 days 09 Dec 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

1 day 06 Dec 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

4 days 09 Dec 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews