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
PatcsPatcs 

How to call batch Apex class using trigger

 how to call the batch Apex class using trigger.

kritinkritin
In trriger just write : reassign.query='SELECT Id, Name, Ownerid FROM Account WHERE ownerid=\'' + u.id + '\''; reassign.email='admin@acme.com'; reassign.fromUserId = u; reassign.toUserId = u2; ID batchprocessid = Database.executeBatch(reassign); here reassign in batch apex class name.
PatcsPatcs

I am calling the batch process like this, while saving it is not showing any error,but when I try to update one record in "Sample object"  it shows me an error "Database.executeBatch should not be called with in a batch or future method"

 

trigger BatchTrgg on sample__c (before update)

{

if(Trigger.isUpdate)

{

for(Sample__c s:Trigger.New)

{

SampleThree st = new SampleThree();

database.executeBatch(st);

}

}

}

kritinkritin
Do one thing in the same batch apex class just define a public method , and in this public method definition it is calling your batch apex execution part. now use this method in your trigger where you wish to call it. like --- public static void startbatchexec(){ batchclass btch1=new batchclass(); ID batchprocessid = Database.executeBatch(btch1); System.debug('Apex Job id: ' + batchprocessid ); }
PatcsPatcs

When I try that

 

while updating the sample object record it shows an error like this

 

"Error:Apex trigger BatchTrgg caused an unexpected exception, contact your administrator: BatchTrgg: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.BatchTrgg: line 7, column 1"

kritinkritin
Post your entire code so that we can understand it. And also check that while querying your record your list record value is there or not means check null.
CLKCLK

Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger will not add more batch jobs than the five that are allowed.

 

As u r calling the executebatch method in a loop , it will exceed the limit.

 

PatcsPatcs

my batch process code is

 

global class SampleCleanUp implements Database.Batchable<sObject>
{
    Public String UserEmail;
    public String emp_r3_num;
    public String emp_area;
    public String Firstname;
    Public String Query;
    global SampleCleanUp()
    {
       
        this.UserEmail=[select Email from User where Id=:UserInfo.getUserId()].Email;
    }
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
           Query='SELECT Owner_R3_Number__c, Owner_Area__c,OwnerId FROM Sample__c ';
           return Database.getQueryLocator(Query);
    }
    global void execute(Database.BatchableContext info,List<Sobject> scope)
    { 
       Sample__c[] tupdates = new Sample__c[]{};
       Sample__c[] tscope = (Sample__c[])scope;
       for(Sample__c tscope1 : tscope)
       {
            emp_r3_num = [select Employee_R3_Number__c from User where Id=:tscope1.OwnerId].Employee_R3_Number__c;
            emp_area = [select Area__c from User where Id=:tscope1.OwnerId].Area__c;
            Firstname = [select FirstName from User where Id=:tscope1.OwnerId].FirstName;


           //checks whether firstname of the User is NULL,if so Updates the fields in Sample as NULL
             if(Firstname == null)
               {
                   tupdates.add(new Target_Account__c(Id=tscope1.Id,Owner_R3_Number__c='Null',Owner_Area__c='Null'));
                }
          
           //If the values in Sample fields are different from that of User Account then update with the values residing in User Account
              else if(emp_r3_num!=tscope1.Owner_R3_Number__c && emp_area!=tscope1.Owner_Area__c)
              {
                       tupdates.add(new Target_Account__c

(Id=tscope1.Id,Owner_R3_Number__c =emp_r3_num,Owner_Area__c=emp_area));
                 }
              else
              { 
                       tupdates.add(new Target_Account__c  (Id=tscope1.Id,Owner_R3_Number__c=emp_r3_num,Owner_Area__c=emp_area));
                }
       }
       if(tupdates.size()>0)
       {
           update(tupdates);
       }
  }
         
    global void finish (Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
        mail.setToAddresses(new String[] {UserEmail});
        mail.setSenderDisplayName('Target Account Batch Job finish'); 
        mail.setSubject('Target Account Processing Complete');  
        mail.setPlainTextBody('Processing of the latest approved modifications has completed.\nView the results via the TAL Batch Updates tab.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
   

}

 

 

My Trigger code is

 

trigger BatchTrgg on sample__c (after update)

{

if(Trigger.isUpdate)

{

for(Sample__c s:Trigger.New)

{

SampleCleanUp  st = new SampleCleanUp();

database.executeBatch(st);

}

}

}

 

kritinkritin
Hi Pacts: define this public method in Batch Apex class, public static void startbatch(){ SampleCleanUp st = new SampleCleanUp(); ID batchprocessid = database.executeBatch(st); System.debug('Apex Job id: ' + batchprocessid ); } now use this method calling in your trigger means do not use database.executeBatch(st); call SampleCleanUp.startbatch();
PatcsPatcs

Now my trigger is like this

PatcsPatcs

Now my trigger is like this

 

trigger BatchTrgg on sample__c (before update) {
if(Trigger.isUpdate)
{
for(Sample__c s:Trigger.New)
{
SampleCleanUp.startBatch();
}
}

}

PatcsPatcs

but it showing the following error

 

Apex script unhandled exception by user/organization: 00590000000JhAy/00D90000000JXDq

Failed to process batch for class 'SampleCleanUp' for job id '707900000005VXz'

caused by: System.DmlException: Update failed. First exception on row 0 with id a0G90000000C3tyEAC; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, BatchTrgg: execution of BeforeUpdate

caused by: System.AsyncException: Database.executeBatch cannot be called from a batch or future method.

Class.SampleCleanUp.startBatch: line 63, column 25

Trigger.BatchTrgg: line 6, column 1: []

Class.SampleCleanUp.execute: line 47, column 12 External entry point

avineesh.mishra361.3951686937406265E12avineesh.mishra361.3951686937406265E12
Hi Patcs,
Please try this code in your trigger:

trigger BatchTrgg on sample__c (before update) {
List<Id> sampleId=new List<Id>();
if(Trigger.isUpdate)
{
     for(Sample__c s:Trigger.New)
     {
      sampleId.add(s.Id);
     }
     if(sampleId.size()>0){
          Database.executeBatch(new SampleCleanUp());
     }

}
}
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)