Friday, August 29, 2014

How to call batch apex from trigger?

How to call batch apex from trigger?


A batch apex can be called from a class as well as from trigger code. But, we have to be very very carefull while calling a batch apex from trigger.

Batch apex

global class BatchApexDemo implements database.batchable<sobject>{
Public string soqlquery;
 Public void setQry(string soqlquery){
    this.soqlquery = 'Select name,status from account limit 1';
 }
 global database.querylocator start(database.batchableContext bc){
   return database.getquerylocator(soqlquery);
 }
 global void execute(database.batchablecontext bd, list<sObject> sc){
   System.debug('**In Execute Method**');
 }
 Public void finish(database.batchableContext bc){
 }
}


Trigger

trigger callbatchapex on Account (after insert) {
 List<account> accList = new List<account>();
 for(account acc : trigger.new){
     if(acc.annualrevenue < 20000)
        accList.add(acc);
 }
    if(accList.size() > 0)
      database.executebatch(new BatchApexDemo(),200);
}






0 comments:

Post a Comment

 
| ,