-
Notifications
You must be signed in to change notification settings - Fork 25
/
cron-pro
executable file
·47 lines (42 loc) · 1.46 KB
/
cron-pro
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/sh
out () { printf %s\\n "$*" ; }
err () { >&2 printf %s\\n "$*" ; }
log () { out $( now ) "$*" }
now () { out $( date -u "+%Y-%m-%dT%H:%M:%SZ" ) }
# Launch a cron job like a professional.
#
# By https://orchestrate.io/blog/2014/03/31/cron-in-production-that-is-a-double-edged-sword/
#
# 1. Use `flock` to create a file write lock.
# 2. Use `sleep` to help distribute workloads across a minute.
# 3. Use `nice` to be friendly with other processes.
# 4. Use `date` with UTC and ISO to timestamp the run.
# 5. Redirect stderr to stdin, suitable for logging.
# 6. Use `while` to read each stdin line, then timestamp it, then log it.
# 7. Always return true.
#
# 1 * * * *
# (
# flock -w 0 200 &&
# sleep $((RANDOM%60)) &&
# nice /command/to/run &&
# date -u "+%Y-%m-%dT%H:%M:%SZ" > /var/run/last_successful_run
# ) 2>&1 200> /var/run/cron_job_lock |
# while read line ; echo `date -u "+%Y-%m-%dT%H:%M:%SZ"` "$line" ; done > /path/to/the/log || true
NAME=${NAME:-$1}
RUNFILE=${LOCKFILE:-/var/run/$USER/$NAME.run}
LOGFILE=${LOGFILE:-/var/log/$USER/$NAME.log}
LOCKFILE=${LOCKFILE:-/var/run/$USER/$NAME.lock}
NICE=${NICE:-/usr/bin/nice}
out "NAME" $NAME
out "LOGFILE" $LOGFILE
out "LOCKFILE" $LOCKFILE
out "EXITFILE" $EXITFILE
out "STRFTIME" $STRFTIME
exec > "$LOGFILE" 2>&1
exec 200>> "$LOCKFILE"
flock -w 0 -x 200
sleep $((RANDOM%60))
$NICE "$@" 2>&1 | while read line ; do log "$line" ; done
EXIT=$?
log $EXIT > "$RUNFILE"