Wednesday, June 4, 2014

How to execute Batch Apex Using Apex Trigger?

How to execute Batch Apex Using Apex Trigger?

In this post i am trying to give an example of how to execute Batch Process from Apex Trigger. Here i am calling Batch class from the 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>();

//Constructor initialization
global UpdateAccountArea(Map<Id, User> owners) {
ownerMap = owners;

//Quuery method.
global Database.QueryLocator start(Database.BatchableContext BC) {
return DataBase.getQueryLocator([SELECT Id,Area__c, OwnerId FROM account WHERE OwnerId IN : ownerMap.keySet()]);

//Execute Method.
global void execute(Database.BatchableContext BC,List<Account> scopeAcc) {

for (Integer i=0;i<scopeAcc.size();i++){
update scopeAcc;

//Finish method to execute at last.
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 });

That's it !!


Post a Comment

| ,