Although the class in Listing 9.1 performs no useful work, it leaves a trail of its activity in the debug log. This is helpful in understanding how Force.com handles your batch-enabled code. It also illustrates the basic elements of a Batch Apex class, listed next:
The class must implement the Database.Batchable
interface. This is a parameterized interface, so you also need to provide a type name. Use SObject for batches with a QueryLocator
scope, or any database object type for an Iterable
scope.
The class must be global. This is a requirement of Batch Apex classes.
global class Listing9_1 implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext context) {
System.debug('start'),
return Database.getQueryLocator(
[SELECT Name FROM Project__c ORDER BY Name]);
}
global void execute(Database.BatchableContext context,
List<SObject> scope) {
System.debug('execute'),
for(SObject rec : scope) {
Project__c p = (Project__c)rec;
System.debug('Project: ' + p.Name);
}
}
global void finish(Database.BatchableContext context) {
System.debug('finish'),
}
}
Before actually running the code in the next subsection, review these implementation details:
The start
method defines the scope by returning a QueryLocator
object constructed from an in-line SOQL statement. The SOQL statement returns all Project records in ascending order by the Name field. The SOQL statement can use parameters (prefaced with a colon) like any in-line SOQL in Apex code. Relationship queries are acceptable, but aggregate queries are not allowed. You can also pass a SOQL string into the getQueryLocator
method, which allows the scope of the batch to be specified with dynamic SOQL.
The execute
method is called once per transaction with a unique group of up to 2,000 records from the scope. The records are provided in the scope
argument.
The finish
method is called when all transactions have completed processing, or the batch job has been interrupted for any reason.
The BatchableContext
object argument in all three methods contains a method for obtaining the unique identifier of the current batch job, getJobID
. This identifier can be used to look up additional information about the batch job in the standard database object AsyncApexJob. You can also pass this identifier to the System.abortJob
method to stop processing of the batch job.
3.139.103.206