0% found this document useful (0 votes)
22 views31 pages

Understanding Batch Apex in Salesforce

The document provides an overview of Asynchronous Apex in Salesforce, detailing its purpose, types, and benefits. It covers four main types: Future Methods, Batch Apex, Queueable Apex, and Scheduled Apex, along with their functionalities and sample code. Additionally, it discusses monitoring asynchronous jobs and includes best practices and interview questions related to Batch Apex.

Uploaded by

ritikssv
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views31 pages

Understanding Batch Apex in Salesforce

The document provides an overview of Asynchronous Apex in Salesforce, detailing its purpose, types, and benefits. It covers four main types: Future Methods, Batch Apex, Queueable Apex, and Scheduled Apex, along with their functionalities and sample code. Additionally, it discusses monitoring asynchronous jobs and includes best practices and interview questions related to Batch Apex.

Uploaded by

ritikssv
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FUTURE QUEUEABLE MONITORING

BATCH SCHEDULAR

Asynchronous Apex
Salesforce Apex Tutorial

@ soham-datta
What is Asynchronous Apex?

It is used to run processes in a separate


thread, at a later time.

It is a process or function that executes a task


"in the background" without the user having to
wait for the task to finish.

It typically uses for callouts to external


systems, operations that require higher limits,
and code that needs to run at a certain time.

The key benefits include:


User efficiency, Scalability, Higher Limits
Types of Asynchronous Apex?

It comes in four different flavors includes:

Future Methods
Batch Apex
Queueable Apex
Scheduled Apex

In upcoming slides we will discuss this in details.


Future Methods

Methods with the @future annotation must be


static methods, and can only return a void type

Typically used for:


Callouts to external Web services.
Operations need to run in their own thread
Isolate DML operations to prevent the
mixed DML error.

Future methods can’t be used in Visualforce


controllers.

Objects can’t be passed as arguments to


future methods.
Future method sample code block

The system collects all asynchronous calls


made after the startTest().

When stopTest() is executed, all these


collected asynchronous processes are then
run synchronously.
Batch Apex

Batch Apex is used to run large jobs (think


thousands or millions of records!) that would
exceed normal processing limits.

This functionality has two awesome


advantages:
Every transaction starts with a new set of
governor limits.
If one batch fails to process successfully,
all other successful batch transactions
aren’t rolled back.

It contains three methods:


start(), execute(), and finish()
Batch apex sample code block

It implements following interfaces including:


[Link]
[Link]
[Link]
Queueable Apex

It is essentially a superset of future methods


with some extra features.

Additional benefits over future method:


1. Queueable class can contain member
variables of non-primitive data types, such as
sObjects or custom Apex types.

2. It returns the ID of the AsyncApexJob record.


You can use this ID to identify your job and
monitor its progress.

3. You can chain one job to another job by


starting a second job from a running job.
Queueable apex sample code block

Best practices:

The execution of a queued job counts once


against the shared limit for asynchronous
Apex method executions.

You can add up to 50 jobs to the queue with


[Link] in a single transaction.
Apex Scheduler

The Apex Scheduler lets you delay execution


so that you can run Apex classes at a
specified time.

This is ideal for daily or weekly maintenance


tasks using Batch Apex.

Schedule class sample code block


Monitoring Asynchronous Jobs

You can monitor the status of all jobs in the


Salesforce user interface.

From Setup -> enter Jobs in the Quick Find box


-> select Apex Jobs.
Let's Connect
@ soham-datta
Nripesh Kumar Joshi

Batch Class in Salesforce

The Batch class is used to process millions of records within normal


processing limits. If you have a lot of records to process then you

s
should go with Batch class.

ie
ig
Batch class has three methods that are following.

od
1. Start Method
2. Execute Method
Pr
3. Finish Method

1. Start Method
ce

This method will collect records or objects on which the operation


or

should be performed.
sf

Syntax of Start Method →


le
Sa

global [Link] start([Link]


BC){}

[Link] interface require a reference to a


[Link] object. Use this object to track the
progress of the batch job.

2. Execute Method
This method processes a subset of the scoped records and performs
operations which we want to perform on the records fetched from the
start method.

Syntax of Execute Method —>

global void execute([Link] BC, list<sobject>) {

s
ie
3. Finish Method

ig
This method executes after all batches are processed. This method is

od
used for any post job or wrap-up work like sending confirmation email
notifications.
Pr
Syntax of Finish Method —>
ce

global void finish([Link] BC) {


or

}
sf

Batch class should be implemented by [Link] interface.


le
Sa

Example —>

global class AccountBatch implements [Link]<sObject>


{
global [Link] start([Link]
BC)
{
String query = 'SELECT Id,Name FROM Account';

return [Link](query);
}
global void execute([Link] BC, List<Account>
scope)
{
for(Account a : scope)
{

s
[Link] = [Link] + 'Updated';

ie
}

ig
update scope;
}

od
global void finish([Link] BC) {
}
Pr
}
ce

[Link] Interface
or

[Link], you can maintain state across these transactions.


sf

For example, if your batch job is executing one logic and you need to
send an email at the end of the batch job with all successful records
le

and failed records. For that, you can use [Link] in the
Sa

class definition.

public class MyBatchJob implements


[Link]<sObject>, [Link]{

public integer summary;

public MyBatchJob(String q){


Summary = 0;
}

public [Link] start([Link]


BC){
return [Link](query);
}

public void execute(

s
[Link] BC,

ie
List<sObject> scope){

ig
for(sObject s : scope){
Summary ++;

od
}
}
Pr
public void finish([Link] BC){
ce

}
}
or
sf

Scheduler Class For Batch Apex


le

Schedulable Class is a global class that implements the Schedulable


Sa

interface. That includes one execute method. Here is example of a


scheduler class.

global class AccountBatchJobscheduled implements Schedulable {


global void execute(SchedulableContext sc) {
AccountBatch b = new AccountBatch();
[Link](b);
}
}

How to Schedule scheduler class

There are two options: we have scheduled the scheduler classes.


1) Declarative Approach
2) By Developer console

s
ie
1. By Declarative Approach →

ig
Step 1) Click on Setup->Apex class. Then search the Schedule Apex

od
button.
Pr
ce
or
sf
le
Sa

Step 2) Execute below code from developer console.

AccountBatchJobscheduled m = new AccountBatchJobscheduled();


String sch = '0 0 0 ? * * * ';
String jobID = [Link]('Merge Job', sch, m);

What is CRON?
CRON is a software utility that is a time-based job scheduler in
Unix-like computer operating systems. Developers who want to set up
and maintain software environments, use this CRON to schedule jobs
(commands or shell scripts) to run periodically at fixed times, dates, or
intervals.

s
ie
What is a CRON expression?

ig
A CRON expression is basically a string of five or six fields separated
by white spaces that represents a set of times, normally as a schedule

od
to execute some routine.
Pr
Use in Salesforce
Use schedule with an Apex class that implements the Schedulable
ce

interface to schedule the class to run at the time specified by a Cron


expression.
or

[Link](JobName, CronExpression, SchedulableClass);


sf

The [Link] method takes three arguments: a name for the


le

job, an expression used to represent the time and date the job is
Sa

scheduled to run, and the name of the class.

CRON expression has the following syntax:


0 0 5 ? * 1,2,3,4,5,6,7
{1} {2} {3} {4} {5} {6}

{1} Seconds - so 0 here i.e. start of the minute.


{2} Minutes - 0 again so start of the hour.
{3} Hours - 5 so 5 am. Uses 24 hour notation so 21 = 9pm

{4} Day_of_month - ? means no specific value, only available for day


of the month and day of the week.

{5} Month - * indicates all values, i.e. every month. (if we only want to
run on 1st Jan say, this would be 1)

{6} Day_of_week - 1,2,3,4,5,6,7 here specifies days 1,2,3,4,5,6,7 in

s
the week. We could also write this string as MON-FRI or preferably as

ie
* to indicate all values.

ig
So this job reads to run at "0 seconds past 0 minutes of the 5th hour
on no specific day of the month for every month of the year for every

od
day of the week".
The following are the values for the expression:
Pr
ce
or
sf
le
Sa
The special characters are defined as follows:

s
ie
ig
od
Pr
ce
or
sf
le
Sa

NOTE: Use the L and W together to specify the last weekday of the
month.
Cron Expression Examples

s
ie
ig
od
Pr
ce
or
sf
le

Example to schedule a class for every 5 min


Sa

[Link](Schedule Job Name 1', '0 00 * * * ?', new


testScheduleFiveMinutes());

[Link](Schedule Job Name 2', '0 05 * * * ?', new


testScheduleFiveMinutes());
[Link](Schedule Job Name 3', '0 10 * * * ?', new
testScheduleFiveMinutes());

[Link](Schedule Job Name 4', '0 15 * * * ?', new


testScheduleFiveMinutes());

[Link](Schedule Job Name 5', '0 20 * * * ?', new


testScheduleFiveMinutes());

s
[Link](Schedule Job Name 6', '0 25 * * * ?', new

ie
testScheduleFiveMinutes());

ig
[Link](Schedule Job Name 7', '0 30 * * * ?', new

od
testScheduleFiveMinutes());
Pr
[Link](Schedule Job Name 8', '0 35 * * * ?', new
testScheduleFiveMinutes());
ce

[Link](Schedule Job Name 9', '0 40 * * * ?', new


or

testScheduleFiveMinutes());
sf

[Link](Schedule Job Name 10', '0 45 * * * ?', new


testScheduleFiveMinutes());
le
Sa

[Link](Schedule Job Name 11', '0 50 * * * ?', new


testScheduleFiveMinutes());

[Link](Schedule Job Name 12', '0 55 * * * ?', new


testScheduleFiveMinutes());
Test Class For Batch Job
How to write a test class for Batch Job.

@isTest
public class AccountBatchTest {
static testMethod void testMethod1() {
List<Account> lstAccount= new List<Account>();
for(Integer i=0 ;i <200;i++) {
Account acc = new Account();

s
[Link] ='Name'+i;

ie
[Link](acc);

ig
}
insert lstAccount;

od
[Link]();
AccountBatch obj = new AccountBatch();
Pr
[Link](obj);
[Link]();
ce

}
}
or
sf

Batch Class Interview Questions


le

● What is a Batch Apex?


Sa

● What is a Schedule apex?


● Where do we need to use Batch apex? What are the Features it
offers?
● What access modifier should we use in Batch Class?
● What are the Methods we should Implement in Batch apex?
● What is the Use of Start method?
● What is the importance of the Execute method? and how many
times it runs?
● What is the purpose of the finish method?
● What is a [Link] interface?
● What is a [Link]?
● What is the iterable<Sobject>?
● What is a [Link]?
● What is the Difference between Synchronous and
Asynchronous?
● Is Batch apex Synchronous or Asynchronous?
● What is the Difference between Stateless Or Stateful?

s
● Is Batch apex Stateless Or Stateful?

ie
● How to Implement Stateful in Batch class?

ig
● How can we schedule a batch class? How?
● Can we schedule Batch classes in Minutes or Hours? If yes,

od
How?
● Can we call one Batch class to another Batch class?
Pr
● Can we schedule a batch apex class with in that batch class?
● Can we call future method from a batch class?
ce

● Can we write batch class and schedulable class in a same


class?
or

● Can we call callouts from batch apex?


● What is the Default batch size? and what is the max batch size?
sf

● How to Execute a Batch Classes?


● How to track the details of the current running Batch job?
le

● What is the AsyncApexJob object?


Sa

● How many batch Jobs Active at a time?


● What are the Batch apex governor limits?
● What are the batch apex Best Practices?
● How to stop the Batch apex jobs?
● How to abort a batch jobs?
● What is BatchApexworker record type?
Nripesh Joshi
Salesforce Developer

Asynchronous Apex Questions


1. Can we call future from future ?

Ans- No, not possible (Channing is possible in queueable)

public class futureMethodExample {

@future
public static void MyFutureMethod(){
Map<Id,Account> mapacct = new Map<Id,Account>([SELECT ID,Name FROM ACCOUNT]);
[Link]('test method'+mapacct);
// MyFutureMethod1(); // You can try to call one future method in another future method
}

@future(callout=true)
public static void MyFutureMethod1(){
Http http = new Http();
HttpRequest request = new HttpRequest();
[Link]('[Link]
[Link]('GET');
// [Link]('>>>>>>>'+id);
HttpResponse response = [Link](request);
Object animals;
String returnValue;

// If the request is successful, parse the JSON response


if ([Link]() == 200) {
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> result = (Map<String, Object>) [Link]([Link]());
[Link]('>>>>>'+[Link]());
animals = [Link]('animal');
[Link](animals);
}

BatchClassPractice bcn = new BatchClassPractice() ; // You can try to call batch class from future method
ID batchprocessid = [Link](bcn);
}
}
2. Can we call batch from schedule apex ?

Ans - Yes, We can call batch from schedule apex.

public class ScheduledBatchClassPractice implements schedulable{

public void execute(SchedulableContext sc){


try{
BatchClassPractice btch = new BatchClassPractice(); // You can call batch class from schedule apex
[Link](btch,400);

// Call the future method in schedulable apex


futureMethodExample.MyFutureMethod1();
}catch(exception e){
[Link]('Exception in ScheduledBatchClassPractice: ' + [Link]());
}

3. Can we call batch from batch ?

Ans - Yes, we can call from finish method but you cannot call in start or excute method.

public with sharing class BatchExample2 implements [Link]<sObject>{


public [Link] start([Link] context) {
return [Link]('SELECT ID, Mark_For_Delete_c FROM Studentc WHERE
Mark_For_Delete_c= \'Yes\'');
}
public void execute([Link] context, List<SObject> records)
{
delete records;
}
public void finish([Link] bc) {
BatchClassPractice btch = new BatchClassPractice();
[Link](btch,200);
}
}

// You can call batch class from batch in finish Method


4. Can we call future from batch ?

Ans- No, we cannot call otherwise Fatal error([Link]) error will occur.
[Link]: Future method cannot be called from a future or batch method:
[Link]()

/* Write a batch a class to update the Teacher's records whose specialization is math */

public class BatchClassPractice implements [Link]<Sobject>, [Link]{

public integer count = 0;

public [Link] start([Link] BC){


String teacherList = 'SELECT Id, Name,Specialization__c FROM Teacher__c WHERE Specialization__c
=\'Math\' OR Specialization__c =\'Physics\'';

return [Link](teacherList);
}
public void execute([Link] BC, List<Teacher__c> tchList){
[Link]();

if(![Link]()){
for(Teacher__c tch: tchList){
if(tch.Specialization__c == 'Math'){
[Link] = 'Sir/Madam'+' '+ [Link];
}if(tch.Specialization__c == 'Physics'){
[Link] = 'Respected Madam'+' '+ [Link];
}
count++;
}
try{
update tchList;
[Link]('Count of Teacher'+count);
}
catch(exception e){
[Link](e);
}

}
}

public void finish([Link] BC){


[Link]();
}
}
5. Can we call batch from future ?

Ans- No, We cannot call otherwise Fatal Error([Link]) error will occur.

FATAL_ERROR [Link]: [Link] cannot be called from a batch start,


batch execute, or future method.

public class futureMethodExample {

@future
public static void MyFutureMethod(){
Map<Id,Account> mapacct = new Map<Id,Account>([SELECT ID,Name FROM ACCOUNT]);
[Link]('test method'+mapacct);
// MyFutureMethod1(); // You can try to call one future method in another future method
}

@future(callout=true)
public static void MyFutureMethod1(){
Http http = new Http();
HttpRequest request = new HttpRequest();
[Link]('[Link]
[Link]('GET');
// [Link]('>>>>>>>'+id);
HttpResponse response = [Link](request);
Object animals;
String returnValue;

// If the request is successful, parse the JSON response


if ([Link]() == 200) {
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> result = (Map<String, Object>) [Link]([Link]());
[Link]('>>>>>'+[Link]());
animals = [Link]('animal');
[Link](animals);
}

BatchClassPractice bcn = new BatchClassPractice() ;


ID batchprocessid = [Link](bcn);
}
}
6. Can we call future and batch from Queueable ?

Ans: Yes we can call future and batch from Queueable and vice-versa.

public class QueuableApexExample implements Queueable {

public static void execute(QueueableContext QC){

Account act = new Account(Name = 'Tested Accctt 97', Phone='0523124578',


isAddress__c=true);
insert act;

futureMethodExample.MyFutureMethod1();

}
}

7. Which interfaces are important in batch ?

Ans: [Link] - It is mandatory in Batch Class


[Link] - It is mandatory while calling callout
[Link] - This Interfaces is used to maintain the state of [Link]’s
suppose you are inserting account and you want to count the all account that
are inserted then you can use this interfaces.

8. What are the methods in batch class?

Ans- Start Method >> Return Type ==> [Link] or Iterable

Execute Method >> Return Type ==> Void

Finish Method >> Return Type ==> Void

[Link] Interfaces in Asynchronous Apex ?

Ans- 1. Queueable,
2. Schedulable,
3. [Link]
10. Can we call future method from Trigger ?

Ans- Yes, We can call future method from trigger.

public class FutureMethodExample2 {

// DML Operation performs on Setup and Non Setup Method in a single transaction
public static void insertSetWithNonSetup(){
Account act = new Account();
[Link] = 'Non Setup Record';
insert act;

//
InsertUserSetup();
[Link](act);
}
@future
public static void insertUserSetup(){

Profile p = [SELECT Id FROM Profile WHERE Name='Cross Org Data Proxy User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User usr = new User();
[Link] ='SetupTest';
[Link] = 'stest';
[Link] = 'nripeshjoshi97@[Link]';
[Link] = [Link];
[Link] = [Link];
insert usr;
[Link](usr);
}

}
Trigger AccountTrigger on Account(Before delete, Before update){

if([Link] && [Link]){


[Link]([Link], [Link],
[Link]);
// [Link](); // Calling Future Method
}
if([Link] && [Link]){
[Link]([Link]);
}
}

11. What are the way of monitor the schedule job ?

Ans: There are two way of monitior the job

1. Apex Jobs Page:


Setup > Apex Jobs to see a list of Apex jobs, including scheduled jobs, their status, and
execution details.
2. Developer Console:
You can use the Developer Console to monitor and debug scheduled jobs. In the Developer
Console, go to the "Query Editor" tab and execute the following query to retrieve scheduled
jobs:

SELECT Id, CronExpression, NextFireTime, PreviousFireTime, StartTime, EndTime, Status,


JobItemsProcessed, TotalJobItems, NumberOfErrors, ExtendedStatus FROM CronTrigger
WHERE [Link] = '7'

12. How can we stop scheduling job ?

Ans: // Retrieve the CronTrigger Id of the scheduled job String jobName = 'YourScheduledJobName';
CronTrigger jobTrigger = [SELECT Id FROM CronTrigger WHERE [Link] = :jobName
LIMIT 1];
// Abort the job using the CronTrigger Id
[Link]([Link]);

You might also like