2

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.

5

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.

3

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
    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 May 3 '17 at 7:29
1

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);
  • Also, what should I do to schedule it every 10 min – Ishan May 3 '17 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 May 3 '17 at 7:31
  • @Ishan this question and its linked questions discuss scheduling less than hourly granularity. – sfdcfox May 3 '17 at 7:31
  • @sfdcfox should I delete this question because I think it is duplicate – Ishan May 3 '17 at 7:32
  • @Ishan A question about scheduling a job "just once" I don't think has ever been clearly answered. Scheduling on a schedule is definitely a duplicate. – sfdcfox May 3 '17 at 7:35

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.