Batch Apex & Schedule Apex in Salesforce

Batch Apex in Salesforce
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

To monitor or stop the execution of the batch Apex job, go to Setup –> Monitoring –> Apex Jobs. For more information, see “Monitoring the Apex Job Queue” in the Salesforce online help.

The Database.Batchable interface contains three methods that must be implemented:

start method

global (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {}
The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.

execute method:

global void execute(Database.BatchableContext BC, list

){}
The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

This method takes the following:
o A reference to the Database.BatchableContext object.
o A list of sObjects, such as List, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records are not guaranteed to execute in the order they are received from the start method.

finish method

global void finish(Database.BatchableContext BC){}

The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.

Batch Apex Governor Limits

Keep in mind the following governor limits for batch Apex:

Up to five queued or active batch jobs are allowed for Apex.
A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors, and five Visualforce cursors open at the same time.
A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
The maximum value for the optional scope parameter is 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records.
If no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.
The start, execute and finish methods can implement only one callout in each method.
Batch executions are limited to one callout per execution.
The maximum number of batch executions is 250,000 per 24 hours.
Only one batch Apex job’s start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they’re started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.

Batch Apex Syntax
Syntax:

global class class_Name Implements Database.Batchable {
global Database.queryLocator start(Database.BatchableContext bc) {
}

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

}

global void finish(Database.BatchableContext bc) {
}
}

To execute:

Class_Name obj = new Class_Name();
Database.executeBatch(obj);

Schedule Apex Syntax:
To schedule:

global class Scheduleclass_Name Implements Schedulable{
global void execute(SchedulableContext sc){
Class_Name obj = new Class_Name();
Database.executeBatch(obj);
}
}

Simple Batch Apex Program:

Showing posts with label Batch Apex in Salesforce. Show all posts
How to delete the records in sobject that are 3 days old records in Salesforce?

Sample Batch:

global class OldRecordDeleteBatch implements Database.Batchable {
global Database.QueryLocator start(Database.BatchableContext bc) {
Date threeDaysBefore = System.today().addDays(-3);
String SOQL = ‘SELECT Id FROM Employee__c WHERE CreatedDate = : threeDaysBefore’;
return Database.getQueryLocator(SOQL);
}

global void execute(Database.BatchableContext bc, List listEmp) {
delete listEmp;
}

global void finish(Database.BatchableContext bc) {
}
}

Showing posts with label Batch Apex in Salesforce. Show all posts
How to delete the records in sobject that are 3 days old records in Salesforce?
Sample Batch:

global class OldRecordDeleteBatch implements Database.Batchable {
global Database.QueryLocator start(Database.BatchableContext bc) {
Date threeDaysBefore = System.today().addDays(-3);
String SOQL = ‘SELECT Id FROM Employee__c WHERE CreatedDate = : threeDaysBefore’;
return Database.getQueryLocator(SOQL);
}

global void execute(Database.BatchableContext bc, List listEmp) {
delete listEmp;
}

global void finish(Database.BatchableContext bc) {
}
}

Example 2:

How to maintain variable value inside the Batch class?
To maintain variable value inside the Batch class, Database.Stateful is used.


Sample Class:

global class Class_Name implements Database.Batchable, Database.Stateful{
Integer i = 0;
global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocatory(‘SELECT Id, Name, Sequence_Number__c FROM Employee__c’);
}

global void execute(Database.BatchableContext bc, List listEmployee){
for(Employee__c e : listEmp){
e.Sequence_Number__c = i;
i += 1;
}
}

global void finish(Database.BatchableContext bc){
}
}

here i value will be maintained even though execute method is called several times.

Example 3:

How to escalate cases using Apex in Salesforce?
Sample Code:

Batch Class:

global class CaseEscalation implements Database.Batchable {
global Database.QueryLocator start(Database.BatchableContext bc){
String SOQL = ‘SELECT Id, IsEscalated FROM Case WHERE Status = \’High\’ AND IsEscalated = False’;
return Database.getQueryLocator(SOQL);
}

global void execute(Database.BatchableContext bc, List caseList){
for(Case c : caseList){
c.IsEscalated = true;
}
update caseList;
}

global void finish(Database.BatchableContext bc){
}
}

Schedulable Class:

global class CaseEscalationSchedule implements Schedulable{
global void execute(SchedulableContext sc){
CaseEscalation ce = new CaseEscalation();
Database.executeBatch(ce);
}
}

Test class for Batch Apex in Salesforce

When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren’t running into governor limits.

The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest around the executeBatch method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the executeBatch method within the startTest and stopTest methods, the batch job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions.

Starting with Apex saved using Salesforce.com API version 22.0, exceptions that occur during the execution of a batch Apex job that is invoked by a test method are now passed to the calling test method, and as a result, causes the test method to fail. If you want to handle exceptions in the test method, enclose the code in try and catch statements. You must place the catch block after the stopTest method. Note however that with Apex saved using Salesforce.com API version 21.0 and earlier, such exceptions don’t get passed to the test method and don’t cause test methods to fail.

Sample Test Class:

@isTest
public class SampleTest {
public static testMethod void testBatch() {
Test.StartTest();
Batch_Class_Name obj = new Batch_Class_Name();
ID batchprocessid = Database.executeBatch(obj );
Test.StopTest();
}
}

Apex Scheduler Limits

Sa1lesforce.com has set some limits on Apex Scheduler. Below are the limits in Apex Scheduler in Salesforce.com.

1. You can only have 100 scheduled Apex jobs at one time(Maximum number of Apex classes scheduled concurrently).

2. The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included.

What is the difference between Database.QueryLocator and Iterable in Batch Apex in Salesforce.?
Database.QueryLocator:

50 Million records can be returned.

Iterable:

Governor limits will be enforced. So, we can use upto 50,000 records only. Else, exception will be thrown.
You can also use the iterable to create your own custom process for iterating through the list.

How to limit number of records to be processed per transaction in Batch Apex?

The Database.executeBatch method takes an optional parameter scope. This parameter specifies the number of records that should be passed into the execute method.

Syntax:

Database.executeBatch(instance of batch class,scope);

Sample:

AccountUpdate au = new AccountUpdate();
Database.executeBatch(au,1500);

The limit for scope parameter is 2000.

The default value is 200.

If the scope value is greater than 2000, it will consider as 2000 and then process.

Cheers!!!

Leave a Comment

Your email address will not be published. Required fields are marked *

Select Language »