PranavNagrecha/AwesomeSalesforceSkills / skills/admin/batch-job-scheduling-and-monitoring
batch-job-scheduling-and-monitoring
VerifiedUse when monitoring, diagnosing, or managing Batch Apex, Scheduled Apex, Queueable, and Flow scheduled jobs: Setup > Apex Jobs, AsyncApexJob queries, concurrent limits, failure detection, and notification patterns. NOT for writing the Batch or Schedulable class itself — use apex/batch-apex-patterns or apex/apex-scheduled-jobs. NOT for BatchApexErrorEvent alerting in code — use apex/scheduled-apex-failure-detection-and-monitoring. Trigger keywords: Setup > Scheduled Jobs, Apex Flex Queue, CronTrigger, CronJobDetail, FlowInterview, System.abortJob, System.schedule, CRON expression, Holding status, BLOCKED state, reschedule after sandbox refresh, scheduled job runbook.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 23.4 KB |
| references/examples.md | markdown | 8.7 KB |
| references/gotchas.md | markdown | 13.5 KB |
| references/llm-anti-patterns.md | markdown | 5.5 KB |
| references/metadata-examples.md | markdown | 23.3 KB |
| references/well-architected.md | markdown | 8.1 KB |
| scripts/check_batch_job_scheduling_and_monitoring.pyexecutable | script | 16.7 KB |
| templates/batch-job-scheduling-and-monitoring-template.md | markdown | 1.5 KB |
references/well-architected.md
View on GitHub# Well-Architected Notes — Batch Job Scheduling And Monitoring
## Relevant Pillars
- **Operational Excellence** — Job monitoring is foundational to operational health. Teams that monitor `AsyncApexJob` actively can detect failures before downstream systems are impacted. Proactive failure notification via `finish()` is a core operational excellence practice.
- **Reliability** — Understanding concurrent job limits (5 Batch Apex) and designing scheduling windows to avoid contention prevents jobs from being stuck in Queued status. Reliable systems plan batch scheduling around these constraints.
- **Scalability** — As orgs grow, batch job volume and frequency increase. Hitting the concurrent job limit is a scalability indicator. Designing batch timing, scope sizes, and job priority helps the platform scale gracefully.
## Architectural Tradeoffs
- **Native Apex Jobs UI vs SOQL monitoring:** The Setup UI is convenient for quick checks but not queryable programmatically. SOQL against `AsyncApexJob` enables building dashboards, triggers, and alerts that the UI cannot. For operational maturity, build SOQL-based monitoring.
- **Email notifications vs centralized logging:** Sending email from `finish()` is simple but not scalable for orgs with many batch jobs. A centralized custom object log (e.g., `Job_Execution_Log__c`) queryable via reports and dashboards is preferable at scale.
- **Batch Apex vs Queueable for background processing:** Batch Apex is designed for large-volume record processing and has monitoring built in. Queueable is lighter weight and has less monitoring visibility. Choose Batch Apex for any job that processes hundreds of records or requires failure tracking.
## Anti-Patterns
1. **Not implementing failure notification in finish()** — Salesforce does not send alerts when batch jobs fail. A batch class without failure notification in `finish()` silently fails — admins discover failures only by checking Setup > Apex Jobs manually.
2. **Scheduling all batch jobs at the same time** — When multiple batch classes are all scheduled at midnight, they queue simultaneously and hit the 5-concurrent-job limit. Stagger job schedules (e.g., one job per 15 minutes) to ensure continuous progression.
3. **Assuming NumberOfErrors=0 means all records succeeded** — If the batch class swallows exceptions in `execute()` without re-throwing, chunks complete with no errors even when records fail. Implement explicit error logging using `Database.SaveResult` in execute() for accurate failure tracking.
4. **Treating the schedule as something the deploy carries** — `CronTrigger` and `CronJobDetail` are org data with no Metadata API type, and a sandbox refresh copies none of them. An org whose only record of "what is scheduled" is the org itself cannot be rebuilt, and cannot be audited. The scheduling registry (`references/metadata-examples.md` section 5) is the artefact that closes this; the checker is what keeps it honest.
5. **Monitoring `Status` and nothing else** — A dashboard filtered to `Status = 'Failed'` misses every ordinary record-level failure, because those complete. It also cannot see a run that never started. Operational monitoring needs three predicates, not one: failures (`Status = 'Failed' OR NumberOfErrors > 0`), overruns (`Processing` beyond the agreed window), and absences (a registry entry with no matching `CronTrigger`).
## Official Sources Used
- Object Reference for the Salesforce Platform — **AsyncApexJob** — https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/object_reference.pdf (JobType and Status restricted picklist values; `NumberOfErrors` counts batches not records; `ExtendedStatus` holds the first error only and full detail is emailed to the last user who modified the class; `ParentJobId` / `BatchApexWorker` chunking; the View Setup and Configuration access rule behind the `Async_Job_Operations` permission set)
- Object Reference for the Salesforce Platform — **CronTrigger and CronJobDetail** — https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/object_reference.pdf (the nine `State` values including `BLOCKED` and `PAUSED_BLOCKED`; `NextFireTime`, `TimesTriggered`, `TimeZoneSidKey`, `OwnerId`; the `CronJobDetail.JobType` codes 1/3/4/6/7/8/9/A that separate Scheduled Flow from Scheduled Apex; Supported Calls being query-only, which is the grounding for "a schedule is data, not metadata")
- Object Reference for the Salesforce Platform — **FlowInterview** — https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/object_reference.pdf (`InterviewStatus` values, the `Error` field added in API 62.0, and the Manage Flow permission needed to delete an interview — the surface behind monitoring query 3g)
- Apex Developer Guide — **Apex Scheduler** and **Holding Batch Jobs in the Apex Flex Queue** — https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm (100 scheduled Apex jobs at one time and how to count them via CronTrigger/CronJobDetail; the `This schedulable class has jobs pending or in progress` deploy error and the delete-deploy-recreate recommendation; sandbox refresh not copying scheduled jobs; the batch status table defining `Completed` as "with or without failure"; flex queue FIFO ordering and the `LimitException` at 100)
- Apex Reference Guide — **System Class** (`abortJob`, `schedule`, `scheduleBatch`) and **FlexQueue Class** — https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_system.htm (the CronTrigger-Id-vs-AsyncApexJob-Id rule for `abortJob`; abort not stopping in-progress code; the six/seven-field CRON syntax, field ranges, special characters and worked expressions; `scheduleBatch` landing at the end of the flex queue; the four `FlexQueue` reorder methods and the "final statement in a transaction" rule; `System.schedule` using the running user's timezone)
- Salesforce Developer Limits and Allocations Quick Reference (App Limits cheat sheet) — https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf (5 batch jobs queued or active concurrently; 100 in the flex queue in Holding; 100 Apex classes scheduled concurrently and 5 in Developer Edition; the `DailyAsyncApexExecutions` allocation of 250,000 or licences × 200; "synchronous limits apply to scheduled Apex jobs"; per-transaction limits resetting per batch `execute`; `OrgLimits.getAll()` / `getMap()` as the way to read remaining budget)
- Metadata API Developer Guide — **Flow / FlowSchedule / FlowStart** and **PermissionSet** — https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/api_meta.pdf (`schedule` required when `triggerType` is `Scheduled`; the `FlowStartFrequency` values and which are segment-triggered only; `startTime` being based on the org's default time zone; the `userPermissions` / `ViewSetup` shape used in the deployable permission set. The absence of any `CronTrigger` or `CronJobDetail` metadata type in this guide is the negative evidence for section 1 of `metadata-examples.md`)
- Salesforce Well-Architected — https://architect.salesforce.com/docs/architect/well-architected/guide/overview.html (Operational Excellence and Reliability framing for the monitoring and registry practices above)
- Apex Developer Guide — Using Batch Apex — https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm (the `finish()` hook and the `Database.BatchableContext.getJobId()` pattern the notification examples rest on — carried over from the original version of this skill)
- Apex Developer Guide — Governor Limits — https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm (per-transaction limit behaviour for batch vs scheduled Apex — carried over from the original version of this skill)
- Salesforce Help — Monitor Apex Jobs — https://help.salesforce.com/s/articleView?id=sf.code_apex_job_monitor.htm&type=5 (the Setup > Apex Jobs UI itself — carried over from the original version of this skill; help.salesforce.com could not be fetched during this revision, so every behavioural claim above is grounded in the PDF guides instead)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |