A First-Principles-Driven Life
04 Dec 2008

Timer In Bash

SYNOPSIS

#function : begin_timer HANDLER_NAME MICROSECONDS CMD_ON_TIMEOUT ARGS...
# @HANDLER_NAME :  handler of timer
# @MICROSECONDS :  micro seconds to wait
# @CMD_ON_TIMEOUT ARGS : command and its arguments to run when timeout
start_timer(){
    [ $# -lt 2 ] && return 1
    HANDLER=$1
    TIMER=$2
    shift 2
    (
        trap exit USR1
        sleep $TIMER
        "$@"
        )&
    eval export $HANDLER=$!
}
export -f start_timer

#function : kill_timer HANDLER_NAME
# @HANDLER_NAME : timer handler to indicate which timer to kill
kill_timer(){
    kill -USR1 ${!1}
}
export -f kill_timer

SAMPLE USAGE

Wait for user input in 5 seconds

#!/bin/sh

trap exit USR1

timeout(){
    echo timeout
    kill -USR1 $1
}

start_timer HANDLER $(( 5 * 1000 * 1000 )) timeout $$
echo -n "READ : "
read F
kill_timer HANDLER
echo "GOT : "$F

Notice

trap TERM HUP QUIT yourself, since if you terminated the process before got any input, timeout event handler will not terminated automatically. You can call killtimer in you trap handler.

Tags: bash
Creative Commons License
A First-Principles-Driven Life by Miao, ZhiCheng is licensed under a Creative Commons Attribution 3.0 License.