Play Around Salesforce Batch Apex And Schedule Apex

Batch Apex

Batch Apex classes are beneficial if the task is something to run large jobs like thousands or millions which is exceeded than normal processing limits. Through batch class one can process the records asynchronously. The specific advantages of using the batch class :

  • If any batch failed and not processed successfully then other successful batch transactions not rolled back.
  • A new transaction starts with new governor limits which make sure that your code runs under their governor limits.

There are three methods which are used in batch class:

  • Start: In the start method, the records are collected which are further utilized in the execute method. Here we can use QueryLocator and Iterable for records retrieval and we can query up to 50 million records by queryLocator that bypassed the governor limit whereas in Iterable the governor limit for fetching records through SOQL is still enforced.
  • Execute: The data under every batch get processed within the execute method. The default size of the batch is 200 records. This method has a reference to Database.BatchableContext object and a list of sObjects i.e List<sObject>. By using Database.QueryLocator we can use the returned list.
  • Finish: This method is used for post-processing operations and it calls once all batch get processed.

Syntax:

global class MyBatchClass implements Database.Batchable<sobject> {
    global (Database.QueryLocator | Iterable<sobject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }
    global void execute(Database.BatchableContext bc, List
 records){
        // process each batch of records
    }    
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    
}

Example:

global with sharing class BatchClassTest implements Database.Batchable&lt;sobject&gt; {
    global Database.QueryLocator Start(Database.BatchableContext bc){
        String query = 'select name,phone,AccountNumber,industry from Account'+
        'where industry =\'Energy\'';
        return Database.getQueryLocator('select name,phone,AccountNumber,industry from Account'+
        ' where industry =\'Energy\'');
    }
    global void execute(Database.BatchableContext bc, List&lt;Account&gt; scope){
        List&lt;Account&gt; account =new List&lt;Account&gt;();
        for(Account acc : scope){
            acc.Name='Energy '+acc.Name;
            // acc.Name=acc.Name.removeStart('Energy Energy Energy Energy ');
            account.add(acc);
        }
        update account;
    }
    global void finish(Database.BatchableContext bc){}
}

For executing batch Class write below code in the developer console, where 1 signifies the no. of records in a batch you can change this value according to requirement.

Advertisement

Database.executeBatch(new BatchClassTest(),1);

Schedule Apex

Schedule apex classes let you schedule the run of your apex classes at the specified time so that the class can run without a delay. An apex class that implements the Schedulable interface for the class determines Schedule apex class. By using System.schedule the method we can schedule a run of an instance of the class at the specified time.

Syntax:

global class SomeClass implements Schedulable {
    global void execute(SchedulableContext ctx) {
        // awesome code here
    }
}

Example:

global class ScheduleClassTest implements Schedulable{
    global void execute(SchedulableContext sc){
        Database.executeBatch(new BatchClassTest(),10);
    }
}

We can schedule jobs in two different ways:

  • By Scheduling a Job from the UI.
    1. From Setup, enter Apex in the Quick Find box, then select Apex Classes.
    2. Click Schedule Apex.
    3. For the job name, enter something like Daily Oppty Reminder.
    4. Click the lookup button next to Apex class and enter * for the search term to get a list of all classes that can be scheduled. In the search results, click the name of your scheduled class.
    5. Select Weekly or Monthly for the frequency and set the frequency desired.
    6. Select the start and end dates, and a preferred start time.
    7. Click Save
  • By Using code in developer console or anyplace inside code.
ScheduleClassTest reminder = new ScheduleClassTest();
// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '20 30 8 10 2 ?'; //10Feb 08:30:20
String jobID = System.schedule('Job Name', sch, reminder);

Thanks For Reading!!
Happy Salesforce!!

Popular Salesforce Blogs