Home SALESFORCEAPEX How to execute Batch Apex Using Apex Trigger

How to execute Batch Apex Using Apex Trigger?

Call your batch Apex class from below trigger,

Trigger:

 trigger UpdateAreaInfoUser on User (after update)  { Map<id, User> owners = new Map<id, User>(); for (Integer i=0;i<Trigger.new.size();i++) { if (Trigger.new[i].Team__c!=Trigger.old[i].Team__c) { owners.put(Trigger.new[i].Id, Trigger.new[i]); } } // 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++){ scopeAcc.get(i).Area__c=ownerMap.get(scopeAcc.get(i).OwnerId).Team__c; } 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[] {'[email protected]'}; mail.setToAddresses(toAddresses); 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.

You may also like

Leave a Comment

*