Select your Language

Batch Apex class

Batch Apex:

1. When you want to process a large number of records on a daily basis or nightly basis or specific time of interval then there is a possibility of encountering the governer limit.

2. To resolve the governer limit issue, we will run the operation as an asynchronous operation using batch apex.

3. Batch apex is exposed as an interface that must be implemented by the developer.

4. Batch jobs can be programmatically invoked at runtime using apex.

5. If you want any apex class to run like batch apex, that apex class has to be implemented an interface database.Batachable interface.

6. Batch apex will break the large set of records into the no of batches with small set of data and every batch run independently from each other with a fresh set of governer limit.

7. Any apex class which implements Dartabase.Batachable interface should define three methods
* Start
* Execute
* Finish

8. Start:
a. This method will be called at the starting of the batch jobs and collects the data on which the batch job need to be operated.

b. Syntax: global Database.QueryLocator Start( Database.batachableContext BC)
/
global Database.Iterable<SObjecct> Start( Database.batachableContext BC)

c. Database.QueryLocator: when you are using a simple query (select) to generate the scope of the records on which batch job should run.

d. If we use QueryLocator , the governer limit for the total no of records retrieved bt the soql query is bypassed and we can fatched up to 50 millions records.

e. Use the Iterable to create a complex scope for the batch job, you can also use the iterable to create your own custom process for iterating through the list.

f. If you are using iterable all governer limit will be still enforced.

g. Start method will break the list of records into no of batches and invoice the Execute method on every batch.

9. Execute

a. This method will be invoked by the start method on every batch of record.

b. This method will contain the business logic that need to be performed on the record fatched from the start method.

c. Syntax: global Database.QueryLocator Start( Database.batachableContext BC)

d. List<Sobject> containing the list of records in the batch job on which this Execute method is running.

Example: If the start method fetched 1000 records and divided them into 5 batches with 200 records in each batch. Then execute method will  be called on every batch  separately ( Execute method will be called 5 times)

9. Finish :
a. This method will be called after executing all the execute method.
b.  This method is used to send notification  email , confirmation email, or Post batch operations.

Syntax: Void Finish (Database.batchableContext).

10. Step to Execute Batch Apex
a. Create a object for the Apex class which implemented the Database.batchable interface

EX: TestBatch obj= new TestBatch();

b Invoke database.executeBatch(object, batchsize)
Batch size can be anything form 1 to 2000. If you don't define the batch size by default it take 200

Id jobid = Database.executeBatch(obj,300);

11. We can track the state of the batch job in two ways.

a. SQL on AsynApex job
AsyncApexJob Job = [select type, status,from AsyncApexJob where id=:jobId];

b. Job under monitor

Setup--> monitor--> jobs--> Apex job

12. How to abort job that is running.

System.abortjob(jobId);

13. Stateful Interface
a. Changes made by one execute will not be transferred to another execute in the batch apex.
b. If you want to transfer the state of the data from batch to another batch we need to implement Database.Stateful interface.
c. When a batch apex class implements Daatabase.stateful interface state of the non static data will be transeferd on execute method to another execute method.

14.Limit:  
At a time only 5 batch job can run .
At a time 100 jobs can add in a flex queue.

15. If any batch fails , only that batch will fails rest batch will execute normally.
16. If Finish method fails that all the changes done by execute method will committed.
17. We can not call the future method from the batch Apex.
18. We can call another batch job from finish method.
19.We can call Webservice from batch apex only if we use interface Database.allowCallouts.


Schedule Apex:

 1. If you want to run the apex class on a specific time then apex class has to be implements schedulable Interface.
2. Syantax: Public class test implements Schedulable
{
}

3. Any apex class which implements schedulable interface has to be dinfine the Excute method.

Public void execute(SchedulableContext sc)
{
}

4. Operation or Logic which you want to schedule should be defined with in the Execute method.

public class testscheExample implements Schedulable{
    public void Execute(SchedulableContext sc)
    {
    list<account> acc= [select id from account where createdDate= THIS_WEEK];
    Delete acc;
    }
}If you want to schedule the class we have to define the Ccron trigger or we can Manually define from apex class list

5. How to schedule job

ID jobId = system.schedule(jobname, CrnExpression, object)

6. We can also schedule the batch apex.
7. we can schedule 100 job at atime
8. if we schedule the job that job not sure to run at the Exact time , it will run when the resources available.

9. Can we call webservice form schedule apex.
NO we can not call webservice from schedulabe apex. if we want then add the webservice in the future method the call the future method from webservice.

It not support synchronous webserive.

10. Can we schedule batch?
yes , we can
  System.scheduleBatch(Object, jobname,minutesFromNow, SizeOfBatch);

11. Any job which is scheduled , it is registered in CronTrigger object






Batch Apex class:

global class BatchExample_2 implements Database.Batchable<Sobject>
{
    global Database.QueryLocator start(Database.BatchableContext bc)
   {
        String query='select id,stagename from Opportunity where createdDate=THIS_MONTH';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc,List<Opportunity> scope)
     {
        for(Opportunity op :scope)
        {
            op.stageName='Closed Won';
        }
        update scope;
    }

    global void finish(Database.BatchableContext bc)
{
        Id jobId=bc.getJobId();
        AsyncApexJob job=[select id ,status,jobType,TotalJobItems from AsyncApexJob where Id=:jobId];
        Messaging.SingleEmailMessage msg =new Messaging.SingleEmailMessage();
        String[] toadd=new String[]{'salesforcebatch300@gmail.com'};
        msg.setToAddresses(toadd);
        msg.setSubject('Batch Operation Status');
        String body='Dear Manager, <br/>  Batch operations completed';
        body=body+'<br/> Job Type :'+job.JobType;
        body=body+'<br/> TotalJobItems:'+job.TotalJobItems;
        body=body+'<br/> Status:'+job.status;
        msg.setHtmlBody(body);
        Messaging.Email[] emails =new Messaging.Email[]{msg};
        Messaging.sendEmail(emails);
    }
}


Execution:
===========
BatchExample_2 o=new BatchExample_2 ();
id jobid=Database.executeBatch(o,5);

2 comments:

  1. hii ..please post the batch apex basics and the methods involved in it

    ReplyDelete
    Replies
    1. Thanks,

      As per your request i have added the basic of Batch Apex and Schedule apex.

      Please Check.

      Delete