Thursday 30 August 2012

Adding a Class that Implements the Schedulable Interface - Apex

Prerequisites:
  • Tutorial #1: Creating Warehouse Custom Objects
  • Tutorial #2: Using the Developer Console
  • Tutorial #8: sObjects and the Database
In this lesson, you’ll write a class that implements the Schedulable interface, which means it can be scheduled to run at a specified date and time.
  1. In the Repository tab, click Classes in the Setup Entity Type section, and then click New.
  2. For the class name, enter MySchedulableClass and click OK.
  3. Delete the auto-generated code and add the following.
    global class MySchedulableClass implements Schedulable {
       global void execute(SchedulableContext ctx) {
          CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
                    FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
    
          System.debug(ct.CronExpression);
          System.debug(ct.TimesTriggered);
    
          Merchandise__c m = new Merchandise__c(
                        Name='Scheduled Job Item',
                        Description__c='Created by the scheduler',
                        Price__c=1,
                        Total_Inventory__c=1000);
          insert m;
       }   
    }
  4. Click Save.

Tell Me More...

  • The declaration of the class contains an extra implements Schedulable at the end. This indicates that the class implements theSchedulable interface and must implement the only method that this interface contains, which is this execute method:
    global void execute(SchedulableContext sc){}
    The parameter of this method is a SchedulableContext object. It provides the getTriggerId method that returns the ID of the CronTrigger API object. After a class has been scheduled, a CronTrigger object is created that represents the scheduled job.
  • The CronTrigger object is queried to get additional information about the scheduled job. The Cron expression and the number of times the job has been run already is written to the debug log.
  • Finally, the execute method creates a merchandise record.

1 comment:

  1. can u please provide the code for executing this code?

    ReplyDelete