rodrigosantosbr

Limit the runtime of a cronjob or script

Feb 17th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

There are ways you can prevent cronjobs from overlapping, but you can also limit how long a particular script can run.

This doesn't just apply to cronjobs but to all scripts, actually, but this guide focusses on cronjobs.

Setting timeouts

The hidden secret is the timeout command. From the manpages:

timeout -- run a command with a time limit

And it's very simple to use.

Limit the time a cronjob can run

To avoid endless cronjobs, change your crontab like this:

$ crontab -l
* * * * * /path/to/your/script.sh

To:

$ crontab -l
* * * * * /bin/timeout -s 2 10 /path/to/your/script.sh

Here's the breakdown:

  • /bin/timeout: the command.
  • -s 2: the signal to send when the timer has exceeded, it can be a number or the name. Equally valid would have been -s SIGINT (more on the kill signals below)
  • 10: the duration the script can run, before the kill signal described above is sent to it.
    So the command above will send the SIGINT signal to the script whenever the timer of 10 seconds has been exceeded.

You can use interesting arguments like --preserve-status to have the timeout command return the same exit code as the script you executed.

The correct kill signal

For a list of valid kill signals, use kill -l.

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL   5) SIGTRAP
 6) SIGABRT  7) SIGBUS   8) SIGFPE   9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT   17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF 28) SIGWINCH    29) SIGIO   30) SIGPWR
31) SIGSYS  34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX

Each of these can be used with its numeric value or the name of the signal

Add Comment
Please, Sign In to add comment