Everything about batch apex

Basically we have three method in Batch Job which are implemented by Database.Batchable Interface
-Start
-Execute
-Finish
Below are the interface we can implement with Apex Batch Job

  • Database.Batchable<sObject>: This is responsible to implement Start, Execute and Finish Method in Apex Batch Job
  • Database.AllowsCallouts : This is responsible for to make call API from Apex Batch class.
  • Database.Stateful: This is Responsible to maintain the state throughout transaction. Variable can be access in all method
  • Database.RaisesPlatformEvents: Call Platform events from Apex Batch class
  • Schedulable : You can directly implement Scheduler into Apex Batch Job and implement Execute Method for scheduling Apex batch Job.

global class myBatchClass implements Database.Batchable<sObject>, Database.AllowsCallouts,
Database.Stateful, Database.RaisesPlatformEvents, Schedulable
{
String query='Select Id ,name from Account';
global database.queryLocator/Iterable<sObject> Start(database.batchableContext bc)
{
       return database.getQyeryLocator(query);
}
global void Execute(database.batchableContext bc, List<sObject> scope)
{
    //Main logic is here
}

global void finish(database.batchableContext bc)
{
//Retireve the current job information
AsyncApexJob a=[Select Id , Status, NumberOfError, JobItemProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:bc.getJobId()];
//Sending Mail
Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
String[] toAddress= new String[]{a.CreatedBy.Email};
mail.setToAddress(toAddress);
mail.setSubject('Status :'+ a.Status);
mail.setPlainTextbody(
'The batch apex job processed '+ a.TotalJobItems + 'batches with : '+ NumberOfError+'failures'
);
Messaging.SendEmail(new Messaging.SingleEmailMessage[]{mail});
}
global void execute(SchedulableContext ctx) {

myBatchClass myBatchObject = new myBatchClass ();
Id batchId = Database.executeBatch(myBatchObject);
}


}


– database.queryLocator : Bypass the soql record limit. it support upto 50 million records.
– If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.
– Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
– ID batchprocessID = Database.executeBatch(mybatch); // execute batch once from dev console. By using this ID you can get information from AsyncApexJob.
– After Database.executeBatch(myBatchJob), this job is placed in Apex Flex Queue and its status set to Holding
– If Apex flex Queue has maximum number of 100 job then Data.executeBatch() thrown LimitException and doesn’t add job in queue.
– you can reorder this job sequence.
– Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);
– JOB Status : Holding, Queued, Preparing, Processing, Aborted, Completed, Failed
– System.scheduleBatch(batchName); to run batch from Developer console.
– Up to 5 batch jobs can be queued or active concurrently.
– Up to 100 Holding batch jobs can be held in the Apex flex queue.
– In a running test, you can submit a maximum of 5 batch jobs.
– We can do DML in start method of Batch Job

Invoking a Batch Class

To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance:

MyBatchClass myBatchObject = new MyBatchClass();
Id batchId = Database.executeBatch(myBatchObject);


You can also optionally pass a second scope parameter to specify the number of records that should be passed into the execute method for each batch. Pro tip: you might want to limit this batch size if you are running into governor limits.

Id batchId = Database.executeBatch(myBatchObject, 100);

Scheduling a Job from the UI

You can also schedule a class using the user interface.
  1. From Setup, enter Apex in the Quick Find box, then select Apex Classes.
  2. Click Schedule Apex.
  3. For the job name, enter something like myBatchClass .
  4. Click the lookup button next to Apex class and enter * for the search term to get a list of all classes that can be scheduled. In the search results, click the name of your scheduled class.
  5. Select Weekly or Monthly for the frequency and set the frequency desired.
  6. Select the start and end dates, and a preferred start time.
  7. Click Save.

Schedule Batch Job Using CRON expression

The System.Schedule method takes three arguments: a name for the job, a CRON expression used to represent the time and date the job is scheduled to run, and the name of the class.

MyBatchClass myBatchObject = new MyBatchClass()l
// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '20 30 8 10 2 ?';
String jobID = System.schedule('myBatchObject ', sch, myBatchObject );

Best Practices

As with future methods, there are a few things you want to keep in mind when using Batch Apex. To ensure fast execution of batch jobs, minimize Web service callout times and tune queries used in your batch Apex code. The longer the batch job executes, the more likely other queued jobs are delayed when many jobs are in the queue. Best practices include:
  • Only use Batch Apex if you have more than one batch of records. If you don’t have enough records to run more than one batch, you are probably better off using Queueable Apex.
  • Tune any SOQL query to gather the records to execute as quickly as possible.
  • Minimize the number of asynchronous requests created to minimize the chance of delays.
  • Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won’t add more batch jobs than the limit.

One thought on “Everything about batch apex

Comments are closed.