1

Can anyone help me scheduling a job on crontab that will run on 12th of each month and if 12th falls on weekends it should run on the next Monday.

I found something from Internet but it's not working

0 0 12 * * [ "$(date +%d -d tomorrow)" == "12" ] && [ "$(date +%u -d 12th)" -gt 5 ] && your-command

This is what ChatGPT gave me. I don't know how to debug this one

1

1 Answer 1

2

My general recommendation is that when you can't trivially format your schedule with the limited syntax that cron provides, you should NOT attempt to create a really complex cron command.

As a work around: run a schedule (slightly) more frequently then you need and then in your batch job, or a wrapper shell script, where you have a much richter environment, you apply the "complex" logic you need. If the batch is allowed to run, execute the job and otherwise exit gracefully.

Example

In cron schedule your batch to run from a wrapper script that always runs on days 12, 13 and 14 or allow it to even run every day.

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  *  command to be executed
25 4 12,13,14 * *   /path/to/your/wrapper.script
# or even: 
25 4 * * *  /path/to/your/wrapper.script

And then in that wrapper shell script you apply the logic:

  • IF today is the 12th AND a weekday:
    run the job ELSE exit gracefully

  • IF today is the 13th AND a Monday:
    (then the 12th was a Sunday and the job wasn't allowed to run)
    run the job ELSE exit gracefully

  • IF today is the 14th AND a Monday:
    (then the 12th was a Saturday and the job wasn't allowed to run)
    run the job ELSE exit gracefully

Your /path/to/your/wrapper.script bash script then could look something like this:

#!/bin/bash
# Wrapper script that will run_batch() on the 12th when 
# the 12th is a weekday, otherwise the following Monday 

run_batch () {
    # Add the real job here
    echo "The job has started"
}

TODAY=$(date +%d) 
#  date +%u     day of week (1..7); 1 is Monday
WEEKDAY=$(date +%u)  

if [ "${TODAY}" -eq 12 ] && [ "${WEEKDAY}" -le 5 ] ; then 
     run_batch
elif [ "${TODAY}" -eq  13 ] && [ "${WEEKDAY}" -eq  1 ] ; then
     run_batch
elif [ "${TODAY}" -eq 14 ] && [ "${WEEKDAY}" -eq  1 ] ; then
    run_batch
else
    exit    
fi

You must log in to answer this question.

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