How to kill a process after a set period of time

 

Knowing how to limit how long a process will run for is quite useful, particularly when you have daily backup scripts and the like which may at times run more than 24 hours; having multiple processes attempting to synchronize the same files can waste time, bandwidth and CPU power needlessly. The command we will use here is timeout. Ubuntu Server should have this pre-installed. It is used so:

 

timeout [no. of seconds] [command]

 

e.g.

 

timeout 10 rsync /home/user/files/ /backups/user/files/

 

would run the above rsync command but kill it after 10 seconds.

 

This can be particularly useful with your daily scripts; simply set the timeout to be a few minutes less than 24 hours and you should hopefully avoid them running over each other. For reference there are 3600 seconds in an hour and 86400 seconds in 24 hours; setting a process to timeout after 86000 seconds would result in it running for 23 hours, 56 minutes and 20 seconds.