Understanding the Batchable Interface

To make your Apex code run as a batch, you must sign a contract with the platform. This contract takes the form of an interface called Batchable that must be implemented by your code. It requires that you structure your processing logic into the following three methods:

Image startThe start method is concerned with the scope of work, the raw set of records to be processed in the batch. When a batch is submitted to Salesforce for processing, the first thing it does is invoke your start method. Your job here is to return a QueryLocator or an Iterable that describes the scope of the batch job.

Image executeAfter calling the start method, Force.com has the means to access all the records you’ve requested that it operate on. It then splits these records into sets of up to 200 records and invokes your execute method repeatedly, once for each set of records. At this point, your code can perform the substance of the batch operation, typically inserting, updating, or deleting records. Each invocation of execute is a separate transaction. If an uncaught exception is in a transaction, no further transactions are processed and the entire batch job is stopped.


Caution

Transactions that complete successfully are never rolled back. So, an error in a transaction stops the batch, but transactions executed up to that point remain in the database. Thinking of an overall Batch Apex job as transactional is dangerous, because this is not its default behavior. Additionally, you cannot use savepoints to achieve a single pseudotransaction across the entire batch job. If you must achieve jobwide rollback, this can be implemented in the form of a compensating batch job that reverses the actions of the failed job.


Image finishThe finish method is invoked once at the end of a batch job. The job ends when all transactions in the scope have been processed successfully, or if processing has failed. Regardless of success or failure, finish is called. There is no requirement to do anything special in the method. You can leave the method body empty if no postprocessing is needed. It simply provides an opportunity for you to receive a notification that processing is complete. You could use this information to clean up any working state or notify the user via email that the batch job is complete.

With this initial walk-through of the Batchable interface, you can begin to apply it to your own trigger or Visualforce controller code. If you find a process that is a candidate to run as a batch, think about how it can be restructured to conform to this interface and thus take advantage of Batch Apex.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.88.142