-
-
Save dreiggy/c906c5deff3da9ec7f0dea2137d81a59 to your computer and use it in GitHub Desktop.
start process if not running, else ignore. Prevents cronjob overlap
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 way to ensure : | |
# | |
# * only one process at the time (prevents process-overlap, handy for 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' | |
# * readable process names in top | |
# | |
# usage: ./lazycron <my-unique-id> <application> [args] | |
# example: ./lazycron cron-my-process php foo.php | |
# ./lazycron cron-my-process bash /home/foo/myscript | |
# ./lazycron cron-my-process bash /home/foo/myscript | |
# | |
# 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 | |
# | |
# tests: https://gist.github.com/coderofsalvation/11254628 | |
PROCESSNAME="$1" | |
BIN="$(which "$2")" | |
PROCESSBIN="/tmp/$(basename $2).$PROCESSNAME" | |
STARTDIR="$(dirname "$(readlink -f "$0")" )/../" | |
EXITCODE=0 | |
STDOUT="/tmp/.lazycron.$PROCESSNAME" | |
LOCKFILE="$STDOUT.lock" | |
NICELEVEL=10 | |
[[ ! -f "$PROCESSBIN" ]] && cp "$BIN" "$PROCESSBIN" | |
shift; shift; # delete the first args | |
trap "rm $LOCKFILE" 0 1 2 3 13 15 # cleanup upon EXIT HUP INT QUIT PIPE TERM | |
cd "$STARTDIR"; exec nice -n $NICELEVEL /usr/bin/flock -w 0 "$LOCKFILE" "$PROCESSBIN" "$@" > "$STDOUT" | |
# output stdout to cron *only* on error | |
EXITCODE=$$; [[ ! $EXITCODE == 0 ]] && cat "$STDOUT" | |
exit $EXITCODE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment