1

I'm trying to schedule a cron job and I'm failing soundly. I'm even starting to think that this can't be done with cron.

I'm trying to set a job that will run at a certain hour every day for six months. Then it should stop for two months and start running again for six months, after which it will stop for two months, run again for six months and so on.

In a nutshell, I want it to run daily for six months, stop two months and start running again for six months in an endless 6 months on/2 months off loop. I can figure a way to do it if a year had 14 months, but sadly it has only 12.

Is it even possible to do this with cron?

TIA

5
  • typo : ... i think that you mean 16 months
    – jsotola
    Sep 16, 2020 at 16:36
  • does your version of cron allow year as a parameter?
    – jsotola
    Sep 16, 2020 at 16:59
  • @jsotola Yes, it allows year as a parameter
    – Peter J.
    Sep 16, 2020 at 17:25
  • two cron jobs ... each run every two years ... assuming january start ... first one starts 2020, runs every month except july/august .... second one starts 2021, runs every month except march/april/november/december
    – jsotola
    Sep 16, 2020 at 20:42
  • I had it set up with a second job that just reminded me of setting the next 6 months after finishing the first 6 months period. I didn't thought that setting several jobs might get me covered for years. Good call, @jsotola. Thanks.
    – Peter J.
    Sep 16, 2020 at 21:15

1 Answer 1

0

There’s no way to fully express your conditions using cron, however it is possible to supplement cron by adding a condition which is evaluated by the shell. The idea here is to tell cron to run your job every day at the appropriate time, then before starting the job, use the shell to check the month.

For example, assuming that your month cycles start on the first day of the month, here’s one way to check the cycle (starting in September 2020):

[[ $((($(date "+%Y*12+10#%m")-(2020*12+9)) % 8)) -lt 6 ]] && ...

This asks date to format the current date as <year>*12+10#<month> (the 10# forces the month to be taken as a base-10 value), then uses that as an arithmetic expression to calculate the number of months elapsed since the start month, and calculate the remainder of the division by 8. Thus in the start month, the result is 0; the following month, 1; six months later, 6, and the cycle restarts after eight months. So comparing the result with 6 determines whether the script should run...

Assuming the shell used in your cron supports such arithmetic operations, you can include this in the cron tab directly; otherwise, include it at the start of your script.

1
  • It works as intended. Thanks. However, I wanted to rely only on cron itself, so I could schedule the job on devices such as Android phones
    – Peter J.
    Sep 16, 2020 at 17:35

You must log in to answer this question.

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