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
Lakshmi SLakshmi S 

Batch apex chaining

Hi All,

Example Program for batch apex chaining and scheduling?
Best Answer chosen by Lakshmi S
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about Batch job
1) http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html

Batch Apex
A Batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.

When to use Batch Apex
One example is if you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up. So in the start() method, you define the query you're going to use in this batch context: 'select Id from Account'. Then the execute() method runs, but only receives a relatively short list of records (default 200). Within the execute(), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block. Thus each time execute() is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute() is complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.

Sample Batch Apex
1) Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

2) Execute Method performs operation which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications.
global class AccountUpdateBatchJob 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 by Batch job';
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) {
    }
}
Calling on Batch Apex

            AccountUpdateBatchJob obj = new AccountUpdateBatchJob();
            DataBase.executeBatch(obj);

Scheduler Class For Batch Apex
global class AccountUpdateBatchJobscheduled implements Schedulable 
{
    global void execute(SchedulableContext sc) 
    {
        AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 
        database.executebatch(b);
    }
}

Call one Batch from Another chaining
global class otherBatchjob 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 by Batch job';
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) 
	{
			// Add batch job calling logic in Finish method
		    AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 
			database.executebatch(b);
    }
}


Let us know if this will help you

Thanks
Amit Chaudhary
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about Batch job
1) http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html

Batch Apex
A Batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.

When to use Batch Apex
One example is if you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up. So in the start() method, you define the query you're going to use in this batch context: 'select Id from Account'. Then the execute() method runs, but only receives a relatively short list of records (default 200). Within the execute(), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block. Thus each time execute() is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute() is complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.

Sample Batch Apex
1) Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

2) Execute Method performs operation which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications.
global class AccountUpdateBatchJob 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 by Batch job';
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) {
    }
}
Calling on Batch Apex

            AccountUpdateBatchJob obj = new AccountUpdateBatchJob();
            DataBase.executeBatch(obj);

Scheduler Class For Batch Apex
global class AccountUpdateBatchJobscheduled implements Schedulable 
{
    global void execute(SchedulableContext sc) 
    {
        AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 
        database.executebatch(b);
    }
}

Call one Batch from Another chaining
global class otherBatchjob 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 by Batch job';
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) 
	{
			// Add batch job calling logic in Finish method
		    AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 
			database.executebatch(b);
    }
}


Let us know if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
NagendraNagendra (Salesforce Developers) 

Hi Lakshmi Narasimha,

Please find the below information for your referene.

Batch Apex Chaining :If you need to run a job after some other processing is done first by another job, you can chain queueable jobs. To chain a job to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an executing job, which means that only one child job can exist for each parent job. For example, if you have a second class called SecondJob that implements the Queueable interface, you can add this class to the queue in theexecute() method as follows:
 

public class AsyncExecutionExample implements Queueable {
    public void execute(QueueableContext context) {
        // Your processing logic here       

        // Chain this job to next job by submitting the next job
        System.enqueueJob(new SecondJob());
    }
}
You can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if Apex is running in test context by calling Test.isRunningTest() before chaining jobs.

Limitations of Batch Apex Chaining :
  • The execution of a queued job counts once against the shared limit for asynchronous Apex method executions.
  • You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
  • No limit is enforced on the depth of chained jobs, which means that you can chain one job to another job and repeat this process with each new child job to link it to a new child job. For Developer Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent queueable job.
Note : When chaining jobs, you can add only one job from an executing job with System.enqueueJob, which means that only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job isn’t supported.

Example for Batch Apex Chaining :A batch consists of a start method (executed once), and execute method (executed multiple times), and a finish method (executed once).  Since the execute method only executes once AND happens after the batches are processed within the execute method, you can simply call the contact batch within the finish method.
global database.querylocator start(Database.BatchableContext BC)
{
  //start method logic here
}

global void execute(Database.BatchableContext BC, List<sObject> scope)
 {
    //start method logic here
}

global void finish(Database.BatchableContext BC)
 {
       //call next batch
       ContactBatch myContactBatch = new ContactBatch();
      Id batchProcessId = Database.executeBatch(myContactBatch);
     //finish method logic here
}
Schedule Apex : Use the Apex scheduler if you have specific Apex classes that you want to run on a regular basis, or to run a batch Apex job using the Salesforce user interface.The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.

Note : Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

To schedule jobs using the Apex scheduler:
  • Implement the Schedulable interface in an Apex class that instantiates the class you want to run.
  • From Setup, enter Apex Classes in the Quick Find box, select Apex Classes, and then click Schedule Apex.
  • Specify the name of a class that you want to schedule.
  • Specify how often the Apex class is to run.
  • For Weekly—specify one or more days of the week the job is to run (such as Monday and Wednesday).
  • For Monthly—specify either the date the job is to run or the day (such as the second Saturday of every month.)
  • Specify the start and end dates for the Apex scheduled class. If you specify a single day, the job only runs once.
  • Specify a preferred start time. The exact time the job starts depends on service availability.
  • Click Save.
Example for Schedule Apex : 

User-added image

Please mark this as the best answer if it helps you

Best Regards,
Nagendra.P

 
Logos MallLogos Mall
Looks promising, can you write my research paper online (https://www.livepaperhelp.com/write-my-research-paper.html)?