Thursday 30 August 2012

Running a Batch Job - Apex

You can invoke a batch class from a trigger, a class, or the Developer Console. There are times when you want to run the batch job at a specified schedule. This shows you how to submit the batch class you created in Lesson 1 through the Developer Console for immediate results. You’ll also create a scheduler class that enables you to schedule the batch class.
Begin by setting up some merchandise records in the organization that don’t have any associated line items. The records that the test created in the previous don’t persist, so you‘ll create some new records to ensure the batch job has some records to process.
  1. Click the Logs tab, and then run the following in the Execute window:
    Merchandise__c[] ml = new List<Merchandise__c>();
    for (Integer i=0;i<250;i++) {
       Merchandise__c m = new Merchandise__c(
           Name='Merchandise ' + i,
           Description__c='Some description',
           Price__c=2,
           Total_Inventory__c=100);
       ml.add(m);
    }
    insert ml;
  2. Click Execute.
    This creates 250 merchandise items, which ensures that our batch class runs twice, once for the first 200 records, and once for the remaining 50 records.
  3. Let’s now submit the batch class by calling Database.executeBatch from the Developer Console. Run the following in the Execute window:
    String query = 'SELECT Id,CreatedDate FROM Merchandise__c ' + 
        'WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)';
    CleanUpRecords c = new CleanUpRecords(query);
    Database.executeBatch(c);
    You’ll receive an email notification for the job’s completion. It might take a few minutes for the email to arrive. The email should state that two batches were run.
  4. To view the status of the batch job execution, click Your Name | Setup | Monitoring | Apex Jobs. Since the job finished, its status shows as completed and you can see that two batches were processed.

    Monitoring the status of a batch job 
  5. To schedule the batch job programmatically, you need to create a class that implements the Schedulable interface which invokes the batch class from its execute method. First, click Your Name | Setup | Develop | Apex Classes | New.
  6. In the code editor box, add the following class definition.
    global class MyScheduler implements Schedulable {
       
       global void execute(SchedulableContext ctx) {
            // The query used by the batch job. 
        
            String query = 'SELECT Id,CreatedDate FROM Merchandise__c ' + 
                            'WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)';
                       
          CleanUpRecords c = new CleanUpRecords(query);
          Database.executeBatch(c);
       }   
    }
  7. Follow steps similar to the ones Lesson 3: Scheduling and Monitoring Scheduled Jobs to schedule the MyScheduler class.

No comments:

Post a Comment