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 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *