Skip to content

Instantly share code, notes, and snippets.

@sc250024
Last active April 29, 2017 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sc250024/df037d8ed48e71d2b64d16ba8fa7df89 to your computer and use it in GitHub Desktop.
Save sc250024/df037d8ed48e71d2b64d16ba8fa7df89 to your computer and use it in GitHub Desktop.
BASH script to check if a cron will run between two specified times
#!/bin/bash
# Specify text file with cron-style schedule, and commands
# Like the following example
# * * * * * /path/to/some/command
# */15 * * * * /path/to/another/command
# * 2,15 * * * /path/to/yet/another/command
# Or pass text via STDIN
CRONFILE="$1"
# Use GNU `date` binary instead of default macOS one
DATE="/usr/local/Cellar/coreutils/8.26/bin/gdate"
# Path to Python; make sure the module
# `croniter` is installed using `pip install croniter`
PYTHON="/usr/local/bin/python"
BEGINDATE="2017-01-13 23:00:00"
ENDDATE="2017-01-14 03:00:00"
BEGINYEAR=$(${DATE} --date="${BEGINDATE}" +%Y)
BEGINMONTH=$(${DATE} --date="${BEGINDATE}" +%m)
BEGINDAY=$(${DATE} --date="${BEGINDATE}" +%d)
BEGINHOUR=$(${DATE} --date="${BEGINDATE}" +%H)
BEGINMINUTE=$(${DATE} --date="${BEGINDATE}" +%M)
BEGINUNIX=$(${DATE} --date="${BEGINDATE}" +%s)
ENDYEAR=$(${DATE} --date="${ENDDATE}" +%Y)
ENDMONTH=$(${DATE} --date="${ENDDATE}" +%m)
ENDDAY=$(${DATE} --date="${ENDDATE}" +%d)
ENDHOUR=$(${DATE} --date="${ENDDATE}" +%H)
ENDMINUTE=$(${DATE} --date="${ENDDATE}" +%M)
ENDUNIX=$(${DATE} --date="${ENDDATE}" +%s)
OUTPUTFILE="crons-${BEGINHOUR}-${ENDHOUR}.txt"
while read line; do
cronminute=$(echo "${line}" | awk '{print $1}')
cronhour=$(echo "${line}" | awk '{print $2}')
cronday=$(echo "${line}" | awk '{print $3}')
cronmonth=$(echo "${line}" | awk '{print $4}')
crondow=$(echo "${line}" | awk '{print $5}')
NEXTRUN=$(${PYTHON} -c "from croniter import croniter;from datetime import datetime;base = datetime(${BEGINYEAR}, ${BEGINMONTH}, ${BEGINDAY}, ${BEGINHOUR}, ${BEGINMINUTE});iter = croniter('${cronminute} ${cronhour} ${cronday} ${cronmonth} ${crondow}', base);print iter.get_next(datetime)")
NEXTRUNUNIX=$(${DATE} --date="${NEXTRUN}" +%s)
if [[ ${NEXTRUNUNIX} -ge ${BEGINUNIX} && ${NEXTRUNUNIX} -le ${ENDUNIX} ]]; then
echo "${line}" >> "${OUTPUTFILE}"
fi
# done < <(cat ${CRONFILE})
done < "${CRONFILE:-/dev/stdin}"
@dayne
Copy link

dayne commented Apr 29, 2017

Neat script.

Not equivalent to what you are doing but just an FYI since your brain is in crontab helper tools. The following website provides a handy web interface to interactively test out and have dynamically described a cronjob schedule.

https://crontab.guru/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment