Bash脚本,自动超时

时间:2014-04-04 12:13:47

标签: bash ssh

我想创建一个运行命令的bash脚本,然后在10分钟后结束它(本身并不困难)。但是,如果再次调用,我希望它将原始脚本的超时重置为0并退出。

目的是让命令在过去10分钟内调用脚本时运行。我确实考虑过文件+时间戳,但它并不是一个优雅的解决方案。也许发出信号?

提前致谢! 詹姆斯

2 个答案:

答案 0 :(得分:2)

在脚本运行时将脚本的进程ID保存到文件中,并在脚本运行完毕后删除该文件。如果存在PID的文件,则可以将其用作条件向进程发送信号以重置计数器。

#Set the counter to 0 at start and reset the counter on receiving signal USR1
i=0
trap "i=0" USR1

#If script already running, send signal to the PID and exit
pid_file=/tmp/myscriptpid
if [[ -e $pid_file ]]
then
  kill -s USR1 $(cat $pid_file)
  exit 0
fi

#Otherwise capture the PID and save to file, clean up on exit
echo "$$" >$pid_file
trap 'rm -f "$pid_file"' EXIT

然后你想要在后台运行你的命令,并在你完成后杀死它:

#Run the command in the background
your_command &
your_command_pid=$!

#Increment $i once each second. 
count() {
  sleep 1
  ((i++))
}

#Note that $i is reset to 0 if the script receives the USR1 signal.
while (( $i < 600 ))
do
  count
done

#Kill the running command once the counter is up to 600 seconds
kill "$your_command_pid"

答案 1 :(得分:0)

你好jleck

检查以下脚本并进行更新。

#!/bin/bash
now=$(date +%s)
final=$(awk 'END {print}' /var/log/count.log 2> /dev/null)
when=$(date --date @${final} 2> /dev/null)

if (($(echo $final | wc -w) > 0)); then
        t1=$(expr $(expr $now - $final) / 60)
        if (($t1 < 30)); then
                time=0
        else
                time=600
        fi
else
        time=600
fi

if (( $time > 0 )); then
        your_command &
        PID=$!
        sleep $time
        kill -9 $PID
        date +%s >> /var/log/count.log
else
        echo "Command Was Executed on $when, Kindly Execute after $(expr 30 - $t1) minutes"
fi

在此之后,第一次执行超时将重置为0,并且将在30分钟差异后10分钟再次执行

相关问题