ApexSensei

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 Processed in one chunk
  • no target Ids → execute never runs, but the marker still gets Batch finished

Requirements:

  1. In start, return Database.getQueryLocator for only the Accounts in accountIds.
  2. In execute, set each Account in scope to Description = 'Processed'.
  3. Update the scope with one DML statement, not one per record.
  4. In finish, set the marker Account's Description to Batch 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.

Try this drill free

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 ›