Schedulable Batch Apex all in a single class?

 In admin, apex, developer, Salesforce, tips & tricks

Batch Apex is super powerful. It lets you manipulate large volumes of data in bite-sized chunks (batches) so you don’t blow Salesforce’s governor limits.

Often we need to schedule our batch apex to run nightly at a specified time. Then you need Scheduled Apex as well.

There are also times when you need to just run a batch job right now and oh, that command isn’t always easy to remember.

What if we could put it all under one roof so you can have an easily started batch job that’s easy to schedule? Of course you can.

Like all batch apex, it implements Database.Batchable thus includes methods for start(), execute(), and finish().

Because it’s implements Schedulable it also includes the requisite execute() method that that interface mandates.

Finally, because it’s super handy to use it includes a second start() method that makes life SO much easier when you want to run the batch right away or schedule it for a certain time every night. If you want to run the batch immediatley, just pass a zero as the time parameter to the start() method and voila! Of course a simple mod, allows you to schedule times more intricate than nightly.


Note:  This is run from the Anonymous Apex window.

// immediately submits the batch job 

// schedules the batch job to run nightly at 1am.

Here’s the code:

global class schedulableBatch implements Database.Batchable<sObject>, schedulable {
    // add Database.Stateful above to make data transcend batches
    String query;

    global schedulableBatch() {

    global Database.QueryLocator start(Database.BatchableContext BC) {
	return Database.getQueryLocator(query);

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
	// execute code

    global void finish(Database.BatchableContext BC) {
	// finish code

    global void execute(SchedulableContext SC) {
 	database.executebatch(new schedulableBatch());

    global static void start(integer hour){
         string jobName = 'job name';
         if (hour == 0) database.executebatch(new schedulableBatch());
	 else {
	     jobName = jobName += ' - ' +;
	     string cron = '0 0 ' + string.valueof(hour) + ' * * ?';
	     system.schedule(jobName, cron, new schedulableBatch());

Of course, you’ll need to modify the batch apex to accomplish your objectives and the test class will need to be updated accordingly, but this give you an easy basic framework to start from.

Additionally, your test class will need to address what the batch apex really does. Be sure to call start to run the batch immediately as well as at a scheduled time to exercise the Schedulable execute() method.

Leave a Comment