Limit the runtime of a cronjob or script

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, May 29, 2016

Follow me on Twitter as @mattiasgeniar

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.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.