How to execute Batch Apex Using Apex Trigger?

Call your batch Apex class from below trigger,


trigger UpdateAreaInfoUser on User (after update)  {
Map<id, User> owners = new Map<id, User>();
for (Integer i=0;i<;i++) {
if ([i].Team__c!=Trigger.old[i].Team__c) {
// You can execute batch apex using trigger using below codes
if (owners.size() > 0) {
Database.executeBatch(new UpdateAccountArea(owners));

Batch Apex Class:

global class UpdateAccountArea implements Database.Batchable<sObject> {
//map of userid - user
Map<Id, User> ownerMap = new Map<Id, User>();
global UpdateAccountArea(Map<Id, User> owners) {
ownerMap = owners;
global Database.QueryLocator start(Database.BatchableContext BC) {
return DataBase.getQueryLocator([SELECT Id,Area__c, OwnerId FROM account WHERE OwnerId IN : ownerMap.keySet()]);
global void execute(Database.BatchableContext BC,List<Account> scopeAcc) {

for (Integer i=0;i<scopeAcc.size();i++){
update scopeAcc;
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {''};
mail.setSubject('Apex Batch Job is done');
mail.setPlainTextBody('The batch Apex Job Processed Successfully');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Database.executeBatch(new UpdateAccountArea(owners)); this is a execute Syntax for the Batch Apex Class.

Written by 

3x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published.