Viveka
Viveka

Reputation: 370

How to set cron expression for multiple time periods

I have a requirement to trigger cron job at 9 am and 10.15 pm every day. i.e the trigger will be as:

next today at 09:00:00
then today at 22:00:00
then today at 22:15:00
then next day at 09:00:00 and so on...

I have done it as * 0,15 9,22 * * * but it will also get triggered at 9.15 am which I don't want. Please help me with creating this expression.

If this is not possible can anyone please suggest how to write multiple cron expressions in time triggered azure function. Here is my code:

[FunctionName("Function1")]
public void Run([TimerTrigger("* 0,15 9,22 * * *")] TimerInfo myTimer, ILogger log)
 {
  //my code here
 }

Upvotes: 1

Views: 2568

Answers (2)

Frank Borzage
Frank Borzage

Reputation: 6816

As far as I know, you can't create such a CRON expression in a Function, I can think of what you need to create two functions. A function CRON Expression: * 0 9,22 * *, another CRON expression: * 15 22 * *.

Upvotes: 2

Kashyap
Kashyap

Reputation: 17534

AFAIK you can not create a cron expressions with different distance between each trigger.

You can solve your problem in multiple ways programmatically:


  • Create a single cron expression that represents the biggest common denominator. E.g.
    • in your example it would be 15 minutes
    • so expression would be 0 0/15 0 ? * * *
  • Make function intelligent enough to decide if it should skip or serve the trigger. E.g. a dumb approach would be:
public class CronFunction {
    private void processEvent(String event) {
        // process...
    }

    @FunctionName("cron")
    public void cronFunc(
        @TimerTrigger(schedule = "0 0 0/1 ? * SAT,SUN *") String event, ExecutionContext context) {
        curr_day = ...;
        curr_time = ...;
        if ((curr_day == today and curr_time in ['09:00:00', '22:00:00', '22:15:00']) ||
           (curr_day == tomorrow and curr_time in ['09:00:00'])) {
                processEvent(event);
        } else {
            logger.debug("skipping trigger");
        }
    }

}

Create multiple triggers, all calling same implementation.

public class CronFunctions {
    private void processEvent(String event) {
        // process...
    }

    @FunctionName("cron1")
    public void cronFunc1(
        @TimerTrigger(schedule = "0 0 0/1 ? * SAT,SUN *") String event, ExecutionContext context) {
        processEvent(event);
    }

    @FunctionName("cron2")
    public void cronFunc2(
        @TimerTrigger(schedule = "0 0/15 0 ? * MON,TUE,WED,THU,FRI *") String event,
        ExecutionContext context) {
        processEvent(event);
    }
}

Upvotes: 1

Related Questions