Tag Archives: Batch Apex

Schedule Batch Apex in Salesforce

Batch Class:

global class accountBatch implements Database.Batchable<sobject> {
  
    global Database.QueryLocator start(Database.BatchableContext bc){
      
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
      
    global void execute(Database.BatchableContext bc, List<account> scope) {
      
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        update scope;
    } 
      
    global void finish(Database.BatchableContext bc) {
      
    }
}

Scheduled Class:

global class accountBatchSchedule implements Schedulable{
	global void execute(SchedulableContext sc) {
		//invoke the batch class
        Database.executeBatch(new accountBatch());
    }
}

There are 2 ways to schedule an apex job:

  • Scheduling a Job from the UI
  • Using the System.Schedule Method

Go to Setup | Apex Class | Click Schedule Apex

  • Enter Job name and select Apex Scheduled Schedulable.
  • Select the Schedulable frequency Weekly or Monthly as per your requirement.
  • Select the start and end dates.
  • Select preferred start time.
  • Click on Save.

Undelete Records in Salesforce Using Batch Apex

Sample Code:

global class AccountUndeleteBatchApex implements Database.Batchable<sObject>{
    
    global Database.queryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Name FROM Account WHERE IsDeleted = True ALL ROWS';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        List<Account> accList = new List<Account>();
        for(Account s:scope){
            //Write your logic
            accList.add(s);
        }
        Undelete accList;
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}

Call Batch Apex From Apex Trigger

Batch Apex Class:

global class AccountBatchApex implements Database.Batchable<sobject>{
    
    global Database.Querylocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
        return database.getquerylocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        for(Account acc: scope){
            //Write your logic
        }  
    }
    
    Public void finish(Database.BatchableContext bc){ 
    }
}

Apex Trigger:

trigger AccountTrigger on Account (after insert) {
    List<Account> accList = new List<Account>();
    for(Account acc : trigger.new){
        if(acc.Type.equals('Customer - Direct')){
            accList.add(acc);
        }
    }
    
    if(accList.size() > 0){
        AccountBatchApex objBatch = new AccountBatchApex();
        Database.executebatch(objBatch,200);
    }
}