How to schedule a class to run once at a specific time from apex

Salesforce gives out of the box ability to schedule apex classes with some limited options to control frequency under setup => apex classes => "Schedule Apex" button. But this approach limits you to run apex classes only at the start of the hour.

If you have a need to run a scheduled apex class at a specific time, you can use custom CRON expressions gives a more flexible way to do that.


//This can be any time in future
Datetime nextRun = System.now().addHours(2);
//Generating cron expression for next run time
String year = String.valueOf(nextRun.year());
String day = String.valueOf(nextRun.day());
String hour = String.valueOf(nextRun.hour());
String min = String.valueOf(nextRun.minute());
String sec = String.valueOf(nextRun.second());
String cronExp = sec + ' ' + min + ' ' + hour + ' '+day+' '+nextRun.format('MMM').toUpperCase()+' ? '+year;
//Scheduling at the specified time
TrackerSchedulable trackerJob = new TrackerSchedulable();
System.schedule('Tracker Job', cronExp, trackerJob);

Note that nextRun can be any datetime value in this case. Here we generate a cron expression from the datetime provided. If you want to read more about cron expressions refer this blog.