Batch Apex Flashcards

Learn about Batch Apex and how it differs from other Asynchronous Operations

1
Q

How does batch apex work ?

A

Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks.

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How many queued or active batch jobs you can have at one time ?

A

You can have only five queued or active batch jobs at one time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to evaluate current count of active/queued batch jobs?

A

You can evaluate the current count by viewing the Scheduled Jobs page in Salesforce or
Programmatically using SOAP API to query the AsyncApexJob object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create a Batch Apex Class ?

A

To use batch apex,
write an Apex Class that implements the Salesforce-provided interface ‘Database.Batchable’ and then invoke the class programmatically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to monitor or stop execution of a Batch Apex Job?

A

To monitor or stop the execution of the batch Apex job from Setup, enter Apex Jobs in the Quick Find box. then select Apex Jobs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the three methods that must be implemented in the Database.Batchable interface ?

A
  1. start method
    public (Database.QueryLocator | Iterable<sObject> ) start(Database.BatchableContext bc) {}
  2. execute method
    public void execute(Database.BatchableContext BC,list<p>){}
  3. finish method
    public void finish(Database.BatchableContext BC){}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the significance of using the start method in Batch Apex ?

A

To collect the records or objects to pass to the interface method execute, call the start method at beginning of batch Apex job.

Method either returns a Database.QueryLocator object or an iterable that contains the records or objects passed to the job.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When to use Database.QueryLocator instead of Iterable in start method in Batch Apex ?

A

When you’re using a simple query (SELECT) to generate the scope of objects in the batch job, use the Database.QueryLocator object.

If you use a QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When to use Iterable instead of Database.QueryLocator Object in start method in Batch Apex ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do enforcement of governor limits differ between Database.QueryLocator object and Iterable object in start method in Batch Apex ?

A

If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the execute method used in Batch Apex for ?

A

public void execute(Database.BatchableContext BC,List<p>){}

To do the required processing for each chunk of data, use the execute method. This method is called for each batch of records that you pass to it.

This method takes the following parameters:
1. A reference to the Database.BatchableContext object.
2. A list of sObjects, such as List<sObject> or a list of parameterized types. If you're using a `Database.QueryLocator`, use the returned list.</sObject>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Is there a set order of execution for the batches in Batch Apex ?

A

Batches of records tend to execute in the order in which they’re received from the start method. The order in which batches of records execute depends on various factors. The order of execution isn’t guaranteed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the finish method in Batch Apex used for ?

A

public void finish(Database.BatchableContext BC)

This method is called after all batches are processed.

Use this method to send confirmation emails or execute post-processing operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Is each execution of a batch Apex job considered a discrete transaction ?

A

Each execution of a batch Apex job is considered a discrete transaction.

For example,
a batch Apex job that contains 1000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records.

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 aren’t rolled back.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

All methods in the Database.Batchable interface require a reference to which object ?

A

All the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object. Use this object to track the progress of the batch job.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which instance method of the Database.BatchableContext object is used for tracking the progress of records in the batch job ?

A

getJobID is the instance method used for tracking the progress of a batch job.

returns : ID

Description :
returns the ID of the AsyncApexJob object associated with this batch job as a string. Use this method to track the progress of records in the batch job.
You can also use this ID with the System.abortJob method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Example of using Database.BatchableContext to query the AsyncApexJob associated with the batch job ?

A
public void finish(Database.BatchableContext BC){
   // Get the ID of the AsyncApexJob representing this batch job
   // from Database.BatchableContext.
   // Query the AsyncApexJob object to retrieve the current job's information.
   AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
      TotalJobItems, CreatedBy.Email
      FROM AsyncApexJob WHERE Id =
      :BC.getJobId()];
   // Send an email to the Apex job's submitter notifying of job completion.
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Apex Sharing Recalculation ' + a.Status);
   mail.setPlainTextBody
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures.');
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to use Iterable in Batch Apex to define Scope ?

A

The start method can return either a Database.QueryLocator object that contains the records to use in the batch job or an iterable. Use an iterable to step through the returned items more easily.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Give an example of a batch apex class using Iterable

A
public class batchClass implements Database.batchable{ 
   public Iterable start(Database.BatchableContext info){ 
       return new CustomAccountIterable(); 
   }     
   public void execute(Database.BatchableContext info, List<Account> scope){
       List<Account> accsToUpdate = new List<Account>();
       for(Account a : scope){ 
           a.Name = 'true'; 
           a.NumberOfEmployees = 70; 
           accsToUpdate.add(a); 
       } 
       update accsToUpdate; 
   }     
   public void finish(Database.BatchableContext info){     
   } 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Which method is used to submit Batch Jobs ?

A

Use the Database.executeBatch method to submit batch jobs.

The Database.executeBatch method takes two parameters:

  • An instance of a class that implements the Database.Batchable interface
  • An optional parameter scope. This parameter specifies the number of records to pass into the execute method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the significance of the optional scope parameter in Database.executeBatch method ?

A

This parameter specifies the number of records to pass into the execute method. Use this parameter when you have many operations for each record being passed in and are running into governor limits.

By limiting the number of records , you are limiting the operations per transaction. This value must be greated than zero.

If the start method of the Batch Class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2000.
If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2000 records.

If the start method of the Batch class returns an iterable, the scope parameter value has no upper limit. However, if you use a high number, you can run into other limits. The optimal scope size is a factor of 2000, for example,100,200,400, and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does the Database.executeBatch method return ?

A

The Database.executeBatch method returns the ID of the AsyncApexJob object, which you can use to track the progress of the job.
Code :

ID batchprocessid = Database.executeBatch(reassign);

AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors 
                    FROM AsyncApexJob WHERE ID =: batchprocessid ];

You can also use this ID with the System.abortJob method.

23
Q

Describe the Apex Flex Queue ?

A

With the Apex Flex Queue , you can submit up to 100 batch jobs.

The outcome of Database.executeBatch is as follows

  • The batch job is placed in the Apex flex queue, and its status is set to Holding.
  • If the Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and doesn’t add the job to the queue.
24
Q

What happens in orgs that don’t have the Apex Flex Queue enabled ?

A

If your org doesn’t have Apex flex queue enabled, Database.executeBatch adds the batch job to the batch job queue with the Queued status. If the concurrent limit of queued or active batch job has been reached, a LimitException is thrown, and the job isn’t queued.

25
Q

What are the ways to reorder jobs in the Apex Flex Queue ?

A

When submitted jobs have a status of Holding, you can reorder them in the Salesforce user interface to control which batch jobs are processed first.
From Setup -> enter Apex Flex Queue in the Quick Find box, then select Apex Flex Queue.

Alternatively, you can use Apex methods to reorder batch jobs in the flex queue. To move a job to a new position, call one of the System.FlexQueue methods. Pass the method the job ID and, if applicable, the ID of the job next to the moved job’s new position.

Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);

26
Q

What are the reasons behind reordering jobs in the Apex Flex Queue ?

A

You can reorder jobs in the Apex flex queue to prioritize jobs.
For example, you can move a batch job up to the first position in the holding queue to be processed first when resources become available.
Otherwise, jobs are processed “first-in,first-out”-in the order in which they’re submitted.

When system resources become available, the system picks up the next job from the top of the Apex flex queue and moves it to the batch job queue.
The system can process up to five queued or active jobs simultaneously for each organization.

The status of these moved jobs changes from Holding to Queued. Queued jobs get executed when the system is ready to process new jobs. You can monitor queued jobs on the Apex Jobs page.

27
Q

What are the possible Batch Job Statuses ?

A

Holding Status :

Job has been submitted and is held in the Apex flex queue until system resources become available to queue the job for processing.

Queued Status :

Job is awaiting execution

Preparing Status:

The start method of the job has been invoked. This status can last a few minutes depending on the size of batch of records.

Processing Status :

Job is being processed.

Aborted Status :

Job aborted by a user.

Completed Status :

Job completed with or without failures

Failed Status :

Job experienced a system failure.

28
Q

What is the System.scheduleBatch method used for ?

A

You can use the System.scheduleBatch method to schedule a batch job to run once at a future time.

The System.scheduleBatch method takes the following parameters:

  • An instance of a class that implements the Database.Batchable interface.
  • The job name
  • The time interval, in minutes, after which the job starts executing.
  • An optional scope value. This parameter specifies the number of records to pass into the execute method.
29
Q

What does the System.scheduleBatch method return ?

A

The System.scheduleBatch method returns the scheduled job ID (CronTrigger ID).

  • This example schedules a batch job to be run 60 minutes from now by calling System.scheduleBatch.
  • The example passes this method an instance of a batch class (the reassign variable), a job name, and a time interval of 60 minutes.
  • The optional scope parameter has been omitted.
  • The method returns the scheduled job ID, which is used to query CronTrigger to get the status of the corresponding scheduled job.
String cronID = System.scheduleBatch(reassign, 'job example', 60);

CronTrigger ct = [SELECT Id, TimesTriggered, NextFireTime
                FROM CronTrigger WHERE Id = :cronID];

// TimesTriggered should be 0 because the job hasn't started yet.
System.assertEquals(0, ct.TimesTriggered);
System.debug('Next fire time: ' + ct.NextFireTime); 
// For example:
// Next fire time: 2013-06-03 13:31:23
30
Q

What are some considerations regarding System.scheduleBatch method ?

A
  • When you call System.scheduleBatch, Salesforce schedules the job for execution at the specified time. Actual execution occurs at or after that time, depending on service availability.
  • The scheduler runs as system - all classes are executed, whether the user has permission to execute the class, or not
  • When the job’s schedule is triggered, the system queues the batch job for processing. If Apex flex queue is enabled in your org, the batch job is added at the end of the flex queue.
  • All scheduled Apex limits apply for batch jobs scheduled using System.scheduleBatch . After the batch job is queued(with a status of Holding or Queued), all batch job limits apply and the job no longer counts toward scheduled Apex limits.
  • After calling this method and before the batch job starts, you can use the returned scheduled job ID to abort the scheduled job using the System.abortJob method.
31
Q

How to use Callouts in Batch Apex ?

A

To use a callout in batch Apex, specify Database.AllowsCallouts in the class definition

public class SearchAndReplace implements Database.Batchable<sObject>,Database.AllowsCallouts{}

Callouts include HTTP requests and methods defined with the webservice keyword.

32
Q

How is Database.Stateful used to maintain state across multiple batch transactions ?

A

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.

If you specify Database.Stateful in the class definition, you can maintain state across these transactions.

  • When using Database.Stateful, only instance member variables retain their values between transactions.
  • Static member variables don’t retain their values and are reset between transactions.
  • Maintaining state is useful for counting or summarizing records as they are processed.
    Example - you could define a method in execute to aggregate totals of opportunity amounts as they were processed

If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values.

33
Q

How to specify a variable to access the initial state of the Batch class ?

A

You can specify a variable to access the initial state of the class.
You can use this variable to share the initial state with all instances of the Database.Batchable methods.

// Implement the interface using a list of Account sObjects
// Note that the initialState variable is declared as final

public class MyBatchable implements Database.Batchable<sObject> {
  private final String initialState;
  String query;
  
  public MyBatchable(String intialState) {
    this.initialState = initialState;
  }

  public Database.QueryLocator start(Database.BatchableContext BC) {
    // Access initialState here 
    
    return Database.getQueryLocator(query);
  }

  public void execute(Database.BatchableContext BC, 
                      List<sObject> batch) {
    // Access initialState here 
    
  }

  public void finish(Database.BatchableContext BC) {
    // Access initialState here 
    
  }
}

The initialState stores only the initial state of the class. You can’t use it to pass information between instances of the class during execution of the batch job.
Example - if you change the value of initialState in execute, the second chunk of processed records can’t access the new value. Only the initial value is accessible.

34
Q

How many executions of the execute method can you test of a Batch Apex in a test class ?

A

When testing your batch Apex, you can test only one execution of the execute method.
Use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren’t running into governor limits.

35
Q

What are some considerations regarding testing batch apex ?

A
  • The executeBatch method starts an an asynchronous process.
  • When you test batch Apex, make certain that the asynchronously processed job is finished before testing against the results.
  • Use the Test methods startTest and stopTest around the executeBatch method to ensure that it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system.
  • When stopTest is executed, all asynchronous processes are run synchronously.
  • If you don’t include the executeBatch method within the startTest and stopTest methods, the batch job executes at the end of your test method. This execution order applies for Apex saved using API version 25.0 and later, but not for earlier versions.
36
Q

How do exceptions that occur during the execution of a batch Apex job behave ?

A
  • For apex saved using API version 22.0 and later, exceptions that occur during the execution of a batch Apex job invoked by a test method are passed to the calling test method.
  • As a result, these exceptions cause the test method to fail. If you want to handle exceptions in the test method, enclose the code in try and catch statements.
  • With Apex saved using Apex version 21.0 and earlier, such exceptions don’t get passed to the test method and don’t cause test methods to fail.
37
Q

Do asynchronous calls such as executeBatch called in a startTest,stopTest block count against your limits for number of queued jobs ?

A

Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, don’t count against your limits for the number of queued jobs.

38
Q

How to enqueue and reorder no-operation jobs within the context of tests ?

A

Use the System.Test.enqueueBatchJobs and System.Test.getFlexQueueOrder methods to enqueue and reorder no-operation jobs within the context of tests.

39
Q

What are the Batch Apex Limitations ?

A
  • 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.
  • The maximum number of batch Apex method executions per 24-hour period is 250,000, or the number of user licenses in your org multiplied by 200- whichever is greater.
  • Method executions include executions of the start,execute and finish methods. The limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, Scheduled Apex and future methods.
  • To check how many asynchronous Apex executions are available, make a request to REST API limits resource.
  • 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.
  • If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2000.
    If set to higher value, Salesforce chunks the records into smaller batches up to 2000 records.
  • If the start method of the batch class returns an iterable, the scope parameter value has no upper limit.
  • 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 records. The system then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.
  • The start,execute and finish methods can implement up to 100 callouts each.
  • Only one batch Apex job’s start method can run at a time in an org. Batch jobs that haven’t started yet remain in the queue until they’re started. 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.
  • Using FOR UPDATE in SOQL queries to lock records during update isn’t applicable to Batch Apex.
40
Q

When does the batch job execute after calling Database.executeBatch method ?

A

When you call Database.executeBatch, Salesforce only places the job in the queue. Actual execution can be delayed based on service availability.

41
Q

Email notifications after running a batch job ?

A

When a batch Apex job is run, email notifications are sent to the user who submitted the batch job.
If the code is included in a managed package and the subscribing org is running the batch job, notifications are sent to the recipient listed in Apex Exception Notification Recipient field.

42
Q

What is BatchApexWorker in batch apex ?

A

For each 10,000 AsyncApexJob records, Apex creates an AsyncApexJob record of type BatchApexWorker for internal use.
When querying for all AsyncApexJob records, it is recommended to filter out records of type BatchApexWorker using the JobType field. Otherwise, the query returns one more record for every 10,000 AsyncApexJob records.

43
Q

What are the only allowed access modifiers for Database.Batchable interface methods ?

A

All implemented Database.Batchable interface methods must be defined as public or global.

44
Q

What is the recommended way to do sharing re-calculations in Batch Apex ?

A

For a sharing recalculation, it is recommended that the execute method delete and then re-create all Apex managed sharing for the records in the batch. This process ensures that sharing is accurate and complete.

45
Q

What happens to batch jobs queued before a Salesforce service maintenance downtime ?

A

Batch jobs queued before a Salesforce service maintenance downtime remain in the queue. After service downtime ends and when system resources become available, the queued batch jobs are executed.

If a batch job was running when downtime occurred, the batch execution is rolled back and restarted after the service comes back up.

46
Q

What are some ways to ensure fast execution of batch jobs ?

A

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.

47
Q

How to chain Batch Jobs ?

A

Starting with API version 26.0, you can start another batch job from an existing batch job to chain jobs together.

You can chain a batch job by calling Database.executeBatch or System.scheduleBatch from the finish method of the current batch class. The new batch job will start after the current batch job finishes.

48
Q

How to chain batch jobs for previous API versions ?

A

For previous API versions, you can’t call Database.executeBatch or System.scheduleBatch from any batch Apex method. The version that’s used is the version of the running batch class that starts or schedules another batch job.

49
Q

What function can firing a platform event from Batch Class achieve ?

A

Batch Apex classes can fire platform events when encountering an error or exception. Clients listening on an event can obtain actionable information, such as how often the event failed and when records were in scope at the time of failure.

Events are also fired for Salesforce Platform internal errors and other uncatchable Apex exceptions such as LimitExceptions, which are caused by reaching governor limits.

50
Q

What is the advantage of firing platform events from the Batch Class over using the Apex Jobs UI ?

A
  • An event message provides more granular error tracking than the Apex Jobs UI.
  • It includes the record IDs being processed, exception type, exception message, and stack trace. You can also incorporate custom handling and retry logic for failures
  • You can invoke custom Apex logic from any trigger on this type of event, so Apex developers can build functionality like custom logging and automated retry handling.
51
Q

Which interface must be implemented for a batch class to fire a platform event ?

A

To fire a platform event, a batch Apex class declaration must implement the Database.RaisesPlatformEvents interface.

public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>, 
   Database.RaisesPlatformEvents{ 
   // class implementation 
}
52
Q

What does the BatchApexErrorEvent object represent ?

A

The BatchApexErrorEvent object represents a platform event associated with a batch Apex class. The object is available in API version 44.0 and later.

If the start,execute or finish method of a batch Apex job encounters a unhandled exception, a BatchApexErrorEvent platform event is fired.

53
Q

How to test BatchApexErrorEvent messages published from Batch Apex Jobs ?

A

Use the Test.getEventBus().deliver() method to deliver event messages that are published by failed batch Apex jobs. Use the Test.startTest() and Test.stopTest() statement block to execute the batch job.

  • Following snippet about how to execute a batch Apex job and deliver event messages.
  • It executes the batch job after Test.stopTest().
  • This batch job publishes a BatchApexErrorEvent message when a failure occurs through the implementation of Database.RaisesPlatformEvents.
  • After Test.stopTest() runs a separate Test.getEventBus().deliver() statement is added so that it can deliver the BatchApexErrorEvent.
try {
    Test.startTest();
    Database.executeBatch(new SampleBatchApex());
    Test.stopTest();
    // Batch Apex job executes here
} catch(Exception e) {
    // Catch any exceptions thrown in the batch job
}

// The batch job fires BatchApexErrorEvent if it fails, so deliver the event.
Test.getEventBus().deliver();