Cron: Difference between revisions

From miki
Jump to navigation Jump to search
(Created page with "== Tips == === Run a cron job with random delay === From [https://stackoverflow.com/questions/9049460/cron-jobs-and-random-times-within-given-hours SO]: <source lang=text> 0 1...")
 
 
(3 intermediate revisions by the same user not shown)
Line 4: Line 4:
<source lang=text>
<source lang=text>
0 1 * * * perl -le 'sleep rand 9000' && *command goes here*
0 1 * * * perl -le 'sleep rand 9000' && *command goes here*
</source>

=== Test script as if run by cron ===
From [https://stackoverflow.com/questions/8132355/test-run-cron-entry/44358180#44358180 SO].

Add cron entry:
<source lang=bash>
* * * * * /usr/bin/env > /home/username/cron-env
</source>

Create a script {{file|run-as-cron}}:
<source lang=bash>
#!/bin/sh
#
# https://stackoverflow.com/questions/8132355/test-run-cron-entry
#
# Add cron entry:
#
# * * * * * /usr/bin/env > /home/username/cron-env
#
# Then:
#
# run-as-cron <cron-environment> <command>
#
# for instance
#
# run-as-cron /home/username/cron-env 'echo $PATH'

. "$1"
exec setsid /usr/bin/env -i "$SHELL" -c "set -a; . $1; $2; echo RC is \$?" </dev/null
</source>
Note:
* <code>setsid</code> makes sure that script will not tied to current tty, and hence run non-interactively
* <code>set -a</code> makes sure that all environment variables are exported correctly.

Now to test script as if run by cron:
<source lang=bash>
run-as-cron ~/cron-env 'echo $PATH'
run-as-cron ~/cron-env ~/somescript.sh
</source>
</source>

Latest revision as of 13:20, 5 June 2017

Tips

Run a cron job with random delay

From SO:

0 1 * * * perl -le 'sleep rand 9000' && *command goes here*

Test script as if run by cron

From SO.

Add cron entry:

 * * * * *  /usr/bin/env > /home/username/cron-env

Create a script run-as-cron:

#!/bin/sh
#
# https://stackoverflow.com/questions/8132355/test-run-cron-entry
#
# Add cron entry:
#
#   * * * * *  /usr/bin/env > /home/username/cron-env
#
# Then:
#
#   run-as-cron <cron-environment> <command>
#
# for instance
#
#   run-as-cron /home/username/cron-env 'echo $PATH'

. "$1"
exec setsid /usr/bin/env -i "$SHELL" -c "set -a; . $1; $2; echo RC is \$?" </dev/null

Note:

  • setsid makes sure that script will not tied to current tty, and hence run non-interactively
  • set -a makes sure that all environment variables are exported correctly.

Now to test script as if run by cron:

run-as-cron ~/cron-env 'echo $PATH'
run-as-cron ~/cron-env ~/somescript.sh