# How can you trigger subsequent asynchronous jobs inside the finish method of a Batch Apex class?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Batch Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/how-can-you-trigger-subsequent-asynchronous-jobs-inside-the-finish-method-of-a-batch-apex-class

## Answer

**Basics:** `finish()` runs once after the last chunk. It is where you send summary emails and start the next stage of a multi-step pipeline (for example load, then recalculate, then notify).

**How it works:**
1. Batch A runs all `execute()` chunks.
2. `finish()` inspects the job (`AsyncApexJob` via `bc.getJobId()`) to see whether errors occurred.
3. If acceptable, it calls `Database.executeBatch(new BatchB(), size)` or enqueues a queueable.
4. B starts when a slot is available (it may wait in the Flex Queue).

**Advanced / deep dive:** `finish()` runs even if some chunks failed, so check `NumberOfErrors` before continuing. Pass results forward through the next job's constructor or through `Database.Stateful` fields. Chained batch jobs are independent jobs: no shared transaction, no automatic rollback. Production chains can be infinite, which is useful for polling loops but dangerous without an exit condition; in Developer Edition the queueable chain depth is 5. For parallel work, start several jobs from `finish()`, remembering the 5-active and 100-Holding limits. For orchestrating many steps with retries, consider a queueable-based state machine with a Finalizer or a custom "pipeline" record that tracks step status.

**Code / config example:**
```apex
public void finish(Database.BatchableContext bc) {
    AsyncApexJob job = [
        SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
        FROM AsyncApexJob WHERE Id = :bc.getJobId()
    ];
    if (job.NumberOfErrors == 0) {
        Database.executeBatch(new RecalculateTotalsBatch(), 200); // next stage
    } else {
        // alert instead of continuing
        System.debug(LoggingLevel.ERROR, 'Stage 1 had ' + job.NumberOfErrors + ' failed chunks');
    }
}
```

**Hidden gotchas & must-remember points:**
- `finish()` runs even when chunks failed.
- The chained batch may sit in Holding if 5 jobs are active.
- Always include a stop condition on recursive chains.
- Don't assume the first job's data is committed for the second if the first used partial success and logged errors.
- Test coverage of chaining in test context can be limited, so guard accordingly.
- `finish()` has synchronous limits for its own work.

**Best practice:** Check the job outcome before chaining, and keep each stage idempotent so a rerun is safe.

---
Source: ForceChallenges · last updated 2026-11-02
