Apex Scheduled Classes and their Constructor Code
By Vincent on February 1, 2011
Just a little lesson learned as to how Scheduled Classes are treated in Salesforce.com.
When a class is scheduled for execution using the “Schedule Apex” button, the class is instantiated immediately and then held in memory until the time it should run. This means that the constructor code of the scheduled class is run when the Admin creates the schedule for the class and not at the time the code is meant to execute.
This is an important distinction and can cause some issues if you’re not careful. Let’s take an example:
global class MyClass implements Schedulable, Database.Stateful{
MyCustomSetting__c settings;
public MyClass(){
settings = MyCustomSetting__c.getInstance();
}
global void execute(ScheduableContext ctx){
String localCopyOfSettingsField = settings.mySettingsField__c;
...
}
}
So in the above code, the MyCustomSettings__c object is loaded at the time the scheduled job is created. So if, for example you have scheduled this class as a weekly job, and you decided to change the value of the mySettingsField__c field after you created this scheduled job, then the Class would not pick up the value for the next scheduled run, as the class has already been instantiated and already taken a reference to it’s copy of the Custom Settings object. You can see how this can be annoying.
If you do find yourself in this situation, you can always delete the scheduled job and re-create it, which would force the code to re-instantiate the class.
The proper long term fix would be to move code that you want to execute at run time into the execute method, since that code has to run at the time of execution.
global class MyClass implements Schedulable, Database.Stateful{
MyCustomSetting__c settings;
public MyClass(){
}
global void execute(ScheduableContext ctx){
settings = MyCustomSetting__c.getInstance();
String localCopy = settings.mySettingsField__c;
...
}
}
RSS feed
More news & opinion »
