Skip to content

Instantly share code, notes, and snippets.

@jeffp123
Created June 3, 2014 03:54
Show Gist options
  • Save jeffp123/f33bb1d9292fd35c1905 to your computer and use it in GitHub Desktop.
Save jeffp123/f33bb1d9292fd35c1905 to your computer and use it in GitHub Desktop.
Exec a script in bash with a time limit
#!/bin/bash
# Get time limit (default is 60 seconds)
if [ $1 == "-t" ]; then
shift
time_limit=$1
shift
else
time_limit=60
fi
# Get command to execute
cmd=$@
echo "About to exec: $cmd"
$cmd &
pid=$!
echo "Starting process with $pid. Now waiting $time_limit seconds..."
sleep $time_limit
echo "Time is up. About to kill process $pid."
kill $pid
echo "Process $pid has been stopped"
@jeffp123
Copy link
Author

jeffp123 commented Jun 3, 2014

To run a service for 1000 seconds, do this:

exec-with-time-limit -t 1000 path/to/service -a arg1 -b -arg2

This is useful with another service, like supervisord, which will force the process to restart after stopping, effectively causing the service to restart every N seconds. It can be a "quick fix" for memory leaks or connection issues. There are probably some other good uses. And it doesn't involve using cron.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment