0

I am developing something custom where I need to save a schedule on some records. This will not be used for salesforce scheduling. But we just require to store a schedule in the most efficient manner. I was hoping to store this as a cron expression. However, we also need to evaluate this to find the next dates in the schedule in order to do some further calculations.

Is there a way how we can evaluate a cron expression in apex without having to write something custom to parse it?

1 Answer 1

2

You could use something like this:

Id jobId = System.schedule('Job','0 0 0 ? * * *', new DummySchedulable());
CronTrigger job = [SELECT NextFireTime FROM CronTrigger WHERE Id = :jobId];
System.abortJob(jobId);
System.debug(job.NextFireTime);

This would give you the next calculated time with absolutely zero effort. Note that this code could fail if the job name were not unique or you're already at 100 scheduled jobs in the org, so you'd have to work that out separately, but this should get you started.

However, this gives you only the next calculated fire time. If you need something better than that, you'll have to do your own parsing/evaluating.

1
  • Nifty little snippet here. Thank you!!
    – DebaSen
    Aug 11, 2021 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.