Dynamically Scheduling Apex to Run at Various Points in Time

All we need is an easy explanation of the problem, so here it is.

I see a lot of documentation on scheduling Apex to run repeatedly (i.e. every day at 1am), or even run once at a specific point in time, but I don’t see anything about dynamically scheduling Apex to run, for example, 5 or 10 minutes from now.

My use case is that our Salesforce org will be receiving messages from an external system at random times, and every time it does, we need to store a token from that system, and pass it to a single scheduled Apex class that will run an hour later. So each class will be running with a different parameter, and at random points in time.

My first thought is that one could try to use system.now() and a Cron expression (i.e. String sch = ’20 30 8 10 2 ?’) to dynamically generate a Cron expression for each job that is scheduled, but that seems overly complicated.

Is there a way to simply specify in Apex “run this five minutes from now?”

Many thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The only “schedule X from now” is for Batchable:

System.scheduleBatch(new BatchClassImpl(), 'Near Future', 5);

This would schedule a job five minutes from now to run the batch job.

For anything else, you would indeed want to build your own cron string, which shouldn’t be more than a dozen lines of code in most cases; you could even write a utility method if this is a common design across multiple Schedulable classes.

You could also technically use a Flow with a Pause element then call some Apex, or use Process Builder, but that involves metadata configuration instead of “just” Apex.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

Leave a Reply