function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sonali  vermasonali verma 

call batch apex class from trigger

friends
can we call Database.executebatch in trigger?
if yes, then how to do and if no what can be the limitation.
concrete example will be helpful

sonali​​​​
surasura
check these two posts . these post are not my own but i think they will help
http://www.cloudforce4u.com/2013/11/call-batch-apex-from-trigger.html (http://theblogreaders.com/how-to-execute-batch-apex-using-apex-trigger/#.VhTrl_nzrIU)

http://www.cloudforce4u.com/2013/11/call-batch-apex-from-trigger.html
sonali  vermasonali verma
Hi
OK we can call batch apex class from trigger.
But documentation doesn't say really much about pitfalls
I understood that we should reduce​​​ scope size say less than 200.
Please let me know any other drawbacks we can run into.

​​
surasura
Hi sonia , 

there is no hard and fast rule on the scope, it depens on the work load of particular batch (SF governor limits apply per batch) . there are certain situations where i have set scoper to 1 and there are situations i have set it to  1000. it all depends on the workload. if  your batch job is a simple operation you can have a higer value for scope and if it is complex it is ideal to use a lesser value.

if you havent already read , please refer this https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm it will give you a comprehensive idea about batch jobs and concerns
farukh sk hdfarukh sk hd
trigger maintrigger on Contact (after insert) {
    Map<id,contact> IdContactMap=new Map<Id,contact>();
    for(Contact con:trigger.new){
        if(con.email!=Null){
            IdContactMap.put(con.id,con);
        }
    }
    if(IdContactMap.size() > 0){
        database.executeBatch(new MailToNewContact(IdContactMap)); // Calling batch class.
    }

}


BATCH APEX CLASS:

global class MailToNewContact implements Database.Batchable<sObject>
{

}

For sample example please refer below url:

HOW TO CALL BATCH APEX CLASS FROM APEX TRIGGER (https://www.sfdc-lightning.com/2019/10/how-to-call-batch-apex-class-from-apex.html)