Can you call a batch class from an Apex trigger? If yes, what are the precautions?
Answer
Yes, via Database.executeBatch(), but with care:
- Limits: only 5 batch jobs can be queued or active at once (extra jobs go to the Flex Queue, up to 100 holding). A trigger firing per 200-record chunk can flood the queue.
- Context: you cannot call
executeBatchfrom a future method, and a batch can only start one batch, from itsfinish(). - Volume: one batch per trigger invocation, not per record. Collect Ids and launch once.
- Recursion: avoid the batch updating the same object and re-triggering infinite batches.
- Check
System.isBatch()/System.isFuture()before enqueuing.
Consider Queueable Apex for lighter work.
apex-triggertriggerasyncbatch