7

I am planning to schedule apex from my class if it meets certain conditions. Is it possible to schedule apex for a single time? If yes is it done using Cron expression or any other method.

3 Answers 3

11

If your class implements Database.Batchable, you can also use System.scheduleBatch to run a batch X minutes in the future. This negates the need for a scheduled class entirely. You can also daisy chain these together if you want to run perpetually every X minutes by calling the batch again in the finish method.

6

Cron expression can we used to run job for any given time. You can schedule for with following expression

0 0 5 1 MAR ? 2019

which means run on enter image description here

You can use following tool to generate your cron expression: http://www.freeformatter.com/cron-expression-generator-quartz.html

Please note that Salesforce doesn't allow wildcard for seconds and minutes. Refer following table for valid cron expression value

enter image description here

1
  • 2
    You've mentioned this tool before, but you should mention that some actual cron expressions are not valid in Apex, such as second or minute wildcards.
    – sfdcfox
    Commented May 3, 2017 at 7:29
3

From the document - Run a scheduled Apex job once

Using Scheduled Apex UI you can not set a scheduled class to run only once, it's always recurring. So, you'll need to use System.scheduled via the system log to implement a workaround.

After the apex is scheduled, Abort the job by adding a finish method to your class that implements the Schedulable Interface. This stops the job from running more than once.

Example code for running a job 10 minutes from now only once

String hour = String.valueOf(Datetime.now().hour());
String min = String.valueOf(Datetime.now().minute() + 10); String ss = String.valueOf(Datetime.now().second());

//parse to cron expression
String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';

MyScheduledJob s = new MyScheduledJob(); System.schedule('Job Started At ' + String.valueOf(Datetime.now()), nextFireTime, s);
8
  • Also, what should I do to schedule it every 10 min
    – Ishan
    Commented May 3, 2017 at 7:29
  • 1
    You have to schedule your batch for 6 times, if you want to run batch for every 10 mints.Go through this - salesforce.stackexchange.com/questions/170829/…
    – Samir
    Commented May 3, 2017 at 7:31
  • @Ishan this question and its linked questions discuss scheduling less than hourly granularity.
    – sfdcfox
    Commented May 3, 2017 at 7:31
  • @sfdcfox should I delete this question because I think it is duplicate
    – Ishan
    Commented May 3, 2017 at 7:32
  • 2
    Is it me or does the code here schedule this to run "10 minutes from now" every day not just "right now"? I'm a cron noob so apologies if I'm missing something. Commented May 19, 2020 at 16:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .