Monitoring Batch Classes in real time
Apex Jobs: Apex jobs can be used to monitor the status of all the running batch jobs in your org. Go to Setup -> Apex Jobs to view all the jobs in your org.
The apex jobs screen can be used to view the status of all the jobs. You can abort a job and check if a job has failed or not.
Status of Apex Jobs
The following are the available values of the status of an apex job :
Status | Description |
Queued | The apex job is awaiting execution and is in the queue for system resources. |
Preparing | The start method of the batch job has been started. |
Processing | The execute method of the batch job has been started and is currently processing. |
Aborted | The batch job was aborted by a user and is not processing anymore. |
Completed | The batch job has finished processing successfully. |
Failed | The batch job failed processing with an error. |
Querying the Batch Job Status in Apex
In order to query the status of an apex job in apex code, we can use the AsyncApexJob object. This object has a record for each batch apex job that is processing in the system.
For example, let’s say we run a batch with the following code :
Id apexJobId = database.executeBatch(new MyBatchClass());
The database.executeBatch method returns a job id, which corresponds to a record in the AsyncApexJob object.
So, we can do something like this in the code :
AsyncApexJob jobInfo = [SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :apexJobId];
We can also query by the name of the apex class name if we do not have the apex job id like this :
AsyncApexJob jobInfo = [SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE ApexClass.Name = ‘MyBatchClass’];