Drills › Work in the background
Build a Batch lifecycle
Work in the background · Advanced · 20 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A clean-up job must process a set of Accounts in chunks and leave a clear marker when it is done.
Implement start, execute, and finish so a Batch job processes selected Accounts and marks completion.
What you will learn
Batch Apex splits a big job into chunks. start returns Database.getQueryLocator([SELECT …]) to pick rows. execute runs once per chunk; scope is List<SObject>, so cast with (Account) item. finish runs once at the end.
Id jobId = Database.executeBatch(new AccountBatch(ids), 200);
Gotcha. A test can run only one execute. Keep test data at or under the batch size and wrap the call in Test.startTest()/Test.stopTest().
The task
Complete the Batch class so execute marks the target Accounts Processed and finish writes Batch finished to a marker Account.
Examples:
- two target Ids and one other Account → only the two targets become
Processed - 200 target Ids, batch size 200 → all 200 become
Processedin one chunk - no target Ids →
executenever runs, but the marker still getsBatch finished
Requirements:
- In
start, returnDatabase.getQueryLocatorfor only the Accounts inaccountIds. - In
execute, set each Account inscopetoDescription = 'Processed'. - Update the scope with one DML statement, not one per record.
- In
finish, set the marker Account'sDescriptiontoBatch finished.
Starter code
public class AS_01C8E9DAF4E0_AccountBatch implements Database.Batchable<SObject> {
private Set<Id> accountIds;
private Id markerId;
public AS_01C8E9DAF4E0_AccountBatch(Set<Id> accountIds, Id markerId) {
this.accountIds = accountIds;
this.markerId = markerId;
}
public Database.QueryLocator start(Database.BatchableContext context) {
return null;
}
public void execute(Database.BatchableContext context, List<SObject> scope) {
}
public void finish(Database.BatchableContext context) {
}
}
When it passes
The checks run the real job with `Database.executeBatch`. Only target Accounts become `Processed`, 200 records update in one chunk, the job completes with no errors, and `finish` writes the marker even when nothing matched.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Carry Account work in a Queueable · Keep counts across Batch transactions ›