What is Batch Apex?
- If we want to process large number of records on daily basis or nightly basis, or specific time of interval then there is a possibility of encountering governing limits.
- To resolve the governing limits issue, we will run the operation as asynchronous operation using batch apex.
- Batch apex will break the larger set of data in to no. of batches, as small set of data & every batch will run independent from each other with fresh set of governing limits.
- If you want to run any Apex class like batch Apex that Apex class has to implement an Interface. Database.Batchable Interface
We have 3 methods in Batch Apex.
- This method will fetch all records on which we want to run the logic.
- Global Database.Querylocatorstart(Database.batchablecontextbc);
- When we are using query(select) to generate the scope of records on which batch job should run, use database.querylocator.
- If we are using Querylocator object, the governing limits for the total number of records retrieved by SOQL queries is bypassed & we can fetch up to 50million records in SOQL query.
- Logic that we want to implement that should be defined here.
- Global void execute(Database.Batchablecontextbc, list<sobject> scope);
List<sobject> contains the list of records in the batch job on which this execute method is running.
- If the start method fetches 1000 records & divided them in to 5batches with 200 records in each batch. Then execute method will be called on every batch separately (execute method will be called 5 times).
This method will be called after executing all the execute methods.
This method is used to spend confirmation emails or post batch operations.
Global void finish(Database.Batchablecontextbc).
Stateful Interface: –
- Changes made by one execute method will not be transferred to another execute in batch Apex.
- If you want to transfer state of data from one batch to another batch we need to implement Database.Stateful Interface.
- When a batch Apex class implements Database.Stateful Interface, state of the non-static data will be transferred from one batch to another.
- Batch size can be anything from 1 to 2000. If we don’t define batch size by default it will take 200.
- If we want to run multiple times then we go for schedule Apex.
Id JobId = Database.executeBatch(cb,5).
Here 5 is batch size.
- Used to write webservice callouts or plugin in batch Apex.
- At a time 5 jobs will be run in a queue, if more than 5 jobs to be run, then it will run in Flex Queue.
- We can add 100 jobs to Flex Queue.
1. Can we call batch apex from trigger?
Yes, we can call but make sure that batch apex will cross governor limits.
2. Can we call batch apex from a batch apex?
Yes, from finish method we can call batch job or batch apex from finish method of another batch job.
3. Can we call future method from
No, we cannot call.