How to run a program for a fixed period of time?

Why not use /usr/bin/timeout?

$ timeout --help
Usage: timeout [OPTION] DURATION COMMAND [ARG]...
  or:  timeout [OPTION]
Start COMMAND, and kill it if still running after DURATION.

I've just wrote the following and it seems to work:

ping google.com& PID=$!; sleep 3; kill $PID

Of course you should substitute ping with the command you want to run and 3 with a timeout in seconds. Let me know if you need a more detailed explanation on how it works.


A simple (and not much tested) version of hatimerun:

#!/bin/sh

help(){
    echo "Usage"  >&2
    echo "  $0 -t TIME COMMAND" >&2
    exit 1
}

TEMP=`getopt -o t: -n "$0" -- "$@"`

if [ $? != 0 ] ; then 
    help
fi

eval set -- "$TEMP"

while true ; do
    case "$1" in
    -t) timeout=$2; shift  2;;
    --) shift; break;;
    esac
done

if [ -z "$timeout" ]; then
 help
fi

cmd="$*"

$cmd&
echo "kill $!" | at now+$timeout

See the manpage of at for how to specify the time. Like with at the minimum time resolution is 1 minute.

Another way is to use upstart instead of this script.