Call Batch Apex class from Trigger

Trigger:

trigger AccountTrigger on Account (after update) {
    List<Account> ack= new List<Account>();
    for (Integer i=0;i<Trigger.new.size();i++) {
        if (Trigger.new[i].Name!=Trigger.old[i].Name) {
            ack.add(Trigger.new[i]);
        }
    }
          Database.executeBatch(new AccountBatchClass(ack));
}

Batch Class with Iterable Start Method:
global class AccountBatchClass implements Database.Batchable<Account>{
 
        List<Account> act= new  List<Account>();
        //Constructor to initialize the values from trigger
        global AccountBatchClass (List<Account> ack){
               
                act=ack;
        }
       
        // Start Method
        global Iterable<Account > start(Database.BatchableContext BC){
        
         return act;
        }
      
      // Execute Method
       global void execute(Database.BatchableContext BC, List<Account>scope){
                delete scope;
                //Your Logic Here
       }
     
       global void finish(Database.BatchableContext BC){
          
        }
    }


 Batch Class with Database.QueryLocator Start Method:

global class AccountBatchClass implements Database.Batchable<Account>{
        List<Account> act= new  List<Account>();
        set<String> st= new set<String>
        //Constructor to initialize the values from trigger
        global AccountBatchClass (List<Account> ack){               
                act=ack;
                for( Account a:ack){
                        st.add(a.Id);
                }
        }
        // Start Method
        global Database.QueryLocator start(Database.BatchableContext BC) {
return DataBase.getQueryLocator([SELECT Id,Area__c, OwnerId FROM account WHERE OwnerId IN : st);
        }
      // Execute Logic
       global void execute(Database.BatchableContext BC, List<Account>scope){
               for (Integer i=0;i<scope.size();i++){
             //Your Logic here
    }
       }     
       global void finish(Database.BatchableContext BC){
          
        }
    }


P.S: Comment Below for any Clarification or help!!

Happy working!! :) :) 

Comments

Popular posts from this blog

Embed Special Characters in VF Page

Error: Compile Error: Illegal conversion from String to System.PageReference

Some Common Errors in the Visual flow