Wednesday 9 August 2017

Batch Apex in Salesforce | how to schedule batch job | Test class for Batch job


Batch Class


Batch class is a class that is used to build complex and long-running process that runs on thousands of records. Batch apex process the records in the chunks.


When to use Batch Apex

Let’s take one example, if you need to update field of any object in your organization. If you have 15,000 or many more records in your org, this is impossible without breaking it up. So we use methods in class then those methods will perform this action. Methods are start(),
Execute() and finish(). So In start() method, you define the query that you are going to use in this batch context : ‘Select Id from SObject’, here Sobject can be any object either standard or custom.
Then the execute() method runs, but receives a short chunk of record(default 200). In the execute method, everything runs in its own transactional context, which means all of the governor limit only apply to that block. Thus each time execute() runs, you are allowed 150 queries and 50,000 DML rows. When execute() completes, a new one is initiated with the next group of records of objects with the new set of governor limits. Finally, finish() method wraps up and runs in the last after all the process has been done. It also use to sending status mail.


Sample Batch Apex Methods-

1   1)  Start method is automatically called at the beginning of the apex job. This method will   collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

2) Execute Method performs operation or perform your business logic which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications.


Let’s take the example on Account objects to process the records and send email after process done:


global class AccountBatchJobApex implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id,Name FROM Account';
       
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        for(Account a : scope)
        {
            a.Name = a.Name + 'Updated by Batch apex’;
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC)
            {
                        System.debug('Send mail after all records has been updated successfuly');
    }
}


Calling On Batch Apex

           
AccountBatchJobApex obj = new AccountBatchJobApex ();
            DataBase.executeBatch(obj);
 


Scheduler Class For Batch Apex
global class AccountUpdateBatchApexscheduled implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        AccountBatchJobApex b = new AccountBatchJobApex ();
        database.executebatch(b);
    }
}         




How to schedule scheduler class

There are two options we can schedule the scheduler class.
1. By System Scheduler
By Developer Console


System Scheduler

Step 1) Click on SetupàApex Class. Then search Schedule Apex button.

After schedule the class you can either check that class is scheduled or not perfectly.  To check schedule class follow steps below-

SetupàScheduled Jobs

 


By Developer Console

 

Execute below code from developer console.

AccountUpdateBatchApexscheduled m = new AccountUpdateBatchApexscheduled ();
String sch = '20 30 8 10 2 ?';
String jobID = system.schedule('Merge Job', sch, m);

 


Test Class

 

@isTest 
public class AccountBatchJobApexTest 
{
    static testMethod void textBatch() 
    {
        List<Account> lstAccount= new List<Account>();
        for(Integer i=0 ;i <200;i++)
        {
            Account acc = new Account();
            acc.Name ='Name'+i;
            lstAccount.add(acc);
        }
        
        insert lstAccount;
        
        Test.startTest();

            AccountBatchJobApex obj = new AccountBatchJobApex();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
}

 

 


Limits in Batch Apex


  1.  The start, execute, and finish methods can implement up to 10 callouts each
  2. The maximum number of batch executions is 250,000 per 24 hours
  3. 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
  4. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.\
  5. Up to five queued or active batch jobs are allowed for Apex
  6. Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
  7. 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
  8. If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 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 the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits.

1 comment:

  1. good explanation thank you......very much....keep posts

    i need in detail explanation on rest api web services....if possible please post....thanks in advance

    ReplyDelete

If you have any doubts, please let me know.