Technology Cares

Not Just another weblog

Posts Tagged ‘apex scheduler’

Flexible Scheduling of Batch Apex Jobs

Posted by Manish on February 7, 2012

Perhaps, one of the most commonly used feature of Salesforce in companies implementing it is Running Batch Jobs to update/delete/insert some records in an Object without having to be interfered by human. Scheduling is something that comes hand on hand when we are talking about running some batch jobs. Like for example run the batch job every monday at 11PM.

In Salesforce, however, through the given UI, it is not possible to schedule the job at lets say 10:30PM/AM. Or Run the job every hour.

For this kind of flexibility, we can use schedule method provided by System class in Salesforce.

Schedule takes three parameters – String JobName, String CronExpression, Object schedulable_class

schedule should be used with the Apex class that implements the Schedulable interface.

Example:

global class BatchActivityScheduler
{
global void BatchActivityScheduler() {}
public static void start()
{
//Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
System.schedule(‘Batch Activity’, ‘0 30 12 7 2 ? 2012’, new invokeBatchActivityUpdate());
}
}

Above class is responsible for scheduling a job on 02/07/2012 12:30 PM. The activity is marked as ‘Batch Activity’ and it will be responsible for calling InvokeBatchActivityUpdate class, which implements Schedulable interface.

global class invokeBatchActivityUpdate implements Schedulable{
global void execute(SchedulableContext SC) {
BatchTaskUpdate t = new BatchTaskUpdate();
database.executebatch(t,200);
}
}

BatchTaskUpdate is the actual class that implements Batchable Interface and has code that we are trying to execute.

global class BatchTaskUpdate implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext info){ }
    global void execute(Database.BatchableContext info, List<sObject> scope){ }
    global void finish(Database.BatchableContext info){ }
}

Now, I can either call my class from, say a custom VisualForce page after a user clicks a button, or via  the execute function in the System Log.

BatchActivityScheduler.start();

Posted in Uncategorized | Tagged: , , | Leave a Comment »