Search code examples
cronhangfire

How to create cron job that is executing every 3 months?


I am using Hangfire in ASP.NET Core for Cron (recurring) Jobs, and I need to create a job that runs every three months starting from a given start date.

So if the start date was 15-Nov-2019, it should run on 15-Nov-2019, 15-Feb-2020, 15-May-2020 and so on and so forth.

And I need it to run every 3 months forever.

So I tried the following cron expression for this: "0 0 15 11/3 ?" or "0 0 15 11/3 *"

But after testing it on this translating site, it tells me that it will run on the following dates:

2019-11-15
2020-11-15
2021-11-15
2022-11-15
2023-11-15

my cron expression after testing it

So, if that is true, then how to make it run every three months starting from 15-Nov-2019 as described above and keep running forever?


Solution

  • The month field in cron takes a number between 1 and 12; depending on the cron implementation used, you could use an explicit list for the month field:

    0 0 15 2,5,8,11 *
    

    or a range with a step:

    0 0 15 2-12/3 *
    

    crontab.guru seems to support a single value with a step as well, but the crontab man page doesn't mention this style, so it might or might not work:

    0 0 15 2/3 *
    

    If you want to be able to set this up more than three months before you want it to run for the first time, you have to manually check the date; in shell (using GNU date), you would do something like this:

    0 0 15 2-12/3 * [ $(date +%%s) -gt $(date -d '2019-11-01' +%%s) ] && yourcommand
    

    This compares the current date to November 1st, 2019; if it is greater than that, the command is run.