Search code examples
cron

Is there a way to run a crontab job on the first Sunday after the 5th of the Month?


I want to run a crontab job on the first Sunday which occurs after the 5th of the month? How would I do this in crontab alone?

I know that to run every Sunday I need to do the following:

0 0 * * SUN

And I think the below would run on all days between the 5th and 11th and on all Sundays in a month

0 0 5-11 * Sun

But I only want to run if the date of the Sunday falls between the 5th and the 11th ( the first Sunday on or after the 5th of the Month)

I guess I could add something like the below to my code, but I'd rather do it in a crontab file alone if possible

import datetime
import os
import sys
dt = datetime.datetime.today()
print(dt.day)

if 5 <= dt.day <= 11:
    os.system('python runner.py')
else:
    print("not the second Sunday of the month")
    sys.exit()

Solution

  • Assuming your cron is similar to the one on my system (Ubuntu 19.10), you can't do it with the time and date fields directly, but you can include the test as part of the shell command within the crontab. The crontab(5) man page has an example:

       # Run on every second Saturday of the month
       0 4 8-14 * *    test $(date +\%u) -eq 6 && echo "2nd Saturday"
    

    So for you this would be

    0 0 5-11 * *    test $(date +\%u) -eq 7 && /run/my/command