-
-
Save shawn-crigger/7e191984ad84a51f51dd to your computer and use it in GitHub Desktop.
cronjob wrapper with locking support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# portable cronjob wrapper to ensure : | |
# | |
# * only one process at the time (prevents process-overlap, handy for unique cron workers) | |
# * reverse cron's email behaviour (only emails on error) | |
# * ultraportable: only reliest on flock, not on debians 'start-stop-daemon' or centos 'daemon' | |
# * nicelevel to tame cpu usage | |
# | |
# usage: cronjoblock <application> [args] | |
# example: cronjoblock /home/foo/myscript & | |
# cronjoblock /home/foo/myscript & <--- 'myscript' will only run when the previous run is finished | |
# | |
# there's is no output unless there are errors. This is handy in respect to cron's MAILTO variable: | |
# the stdout/stderr output will be suppressed (so cron will not send mails) *unless* the given process | |
# has an exitcode > 0 | |
# | |
[[ ! -n $1 ]] && { head -n11 $0 | sed 's/^#/ /g' | grep -v 'bin\/bash'; exit; } | |
EXITCODE=0 | |
STDOUT="/tmp/.cronjoblock.$( echo "$*" | tr A-Z a-z | sed -e 's/[^a-zA-Z0-9\-]/-/g')" | |
LOCKFILE="$STDOUT.lock" | |
NICELEVEL=10 | |
exec nice -n $NICELEVEL /usr/bin/flock -w 0 "$LOCKFILE" "$@" > "$STDOUT" | |
EXITCODE=$$; [[ ! $EXITCODE == 0 ]] && cat "$STDOUT" # output stdout to cron *only* on error | |
exit $EXITCODE # let cron know (trigger email) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SHELL=/bin/bash | |
MAILTO="onlybugs@mycompany.com" | |
# -------------- min (0 - 59) | |
# | --------------- hour (0 - 23) | |
# | | ---------------- day of month (1 - 31) | |
# | | | ----------------- month (1 - 12) | |
# | | | | ------------------ day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) | |
# | | | | | | |
# | | | | | | |
# * * * * * command to execute | |
*/5 * * * * cd /my/path && ./cronjoblock foo bar # run every 5 mins if not running |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment