Friday 22 March 2013


Apex batches can be scheduled via the browser as often as one day, but with code they can be scheduled as often as every hour using the CronExpression explained here. This is the code you need:
You need a class that implements the Schedulable interface global class:
1
2
3
4
5
6
7
8
9
10
scheduler implements Schedulable {
    global void execute(SchedulableContext SC) {
        schedule s = new schedule();
        s.DoMethod();
    }
    public static void schedule(String name, String strSched) {
        scheduler s = new scheduler();
        system.schedule(name, strSched, s);
    }
}
When the time arrives, it will execute this class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class schedule {
    public schedule() {
        System.debug('SFDC: Constructor');
    }
    public void DoMethod() {
        System.debug('APF: Constructor');
        // This is where you do the [SELECT .... LIMIT 100]
        List<YourObject__c> recordsToProcess = [SELECT ....WHERE .... LIMIT 100];
        for (YourObject__c yo : recordsToProcess) {
            yo.aField__c = aValue;
        }
        Update toProcess
    }
}
Finally, this class can be scheduled with this instruction:
Scheduler.schedule('Bottom of every hour', '0 30 * * * ?');
So the code will be executed at the bottom of every hour.
But what if you want it to run every 20 minutes? Well, you can't do it with a single schedule, but you could do it with multiple schedules like this:
1
2
3
Scheduler.schedule('At :00', '0 00 * * * ?');
Scheduler.schedule('At :20', '0 20 * * * ?');
Scheduler.schedule('At :40', '0 40 * * * ?');
Categories: ,

1 comment:

  1. Hello!
    Our company developed a package which allows you to run jobs multiple times a day/even every 5 mins/every hour and more/etc. Available on AppExchange for free: https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000DqCmYUAV

    ReplyDelete

    Links