Linux: Killing Processes After a Set Period of Time

Here is a simple bash shell script to run a process and automatically stop it after a set period of minutes / time. I use this in cron, so I will give my crontab entry first:

#in this cron entry: cd to /usr/local, run script_start at 3:00 pm M-F
#and kill it after 300 minutes if it is still running
00 15 * * 1,2,3,4,5 cd /usr/local/&&./delay_kill ./script_start 300

Here is the delay_kill script which handles killing the job after x minutes: 

#!/bin/bash
#start scheduled job and kill it after a specified amount of minutes

: ${1?”Usage: $0 COMMAND_TO_EXECUTE MINUTES”}

logger $1 ’started’

# this is the command to run
$1 &

PROC_ID=$!

SLEEPTIME=$(( 60 * $2 ))
# echo “sleeping for $SLEEPTIME seconds”
sleep $SLEEPTIME

if [ -d "/proc/$PROC_ID" ]; then
       kill -hup $PROC_ID
fi

logger $1 ’script completed’

Leave a Reply