bash脚本:自上次运行后等待几秒钟

时间:2018-01-11 22:44:28

标签: bash

如何编写自上次运行以来延迟执行命令几秒钟的bash脚本? 我的意思是存储最后执行时间的某个地方,计算差异到当前时间然后睡觉,比如5秒,如果最后一次运行不到5秒。

2 个答案:

答案 0 :(得分:1)

我要问自己的第一个问题是,"我是否真的需要延迟执行这些命令的脚本?"如果您可以并行运行多个命令,然后等待每个进程使用wait命令完成,那么这通常更快,更可取。看一下讨论the difference between wait and sleep

的SO问题

那就是说,如果你真的需要等待至少五秒钟,你可以做这样的事情:

#!/bin/bash
export delay_seconds=5
export start_time=`date +%s`

#Run some commands here...

seconds_since_start=`expr \`date +%s\` - $start_time`

if [ $seconds_since_start -lt $delay_seconds ]; then
    time_remaining=`expr $delay_seconds - $seconds_since_start` 
    echo "Sleeping "$time_remaining" seconds..."
    sleep $time_remaining
else
    echo $seconds_since_start" seconds have already passed since the commands above started.  Continuing..."
fi

echo "Script finished."

答案 1 :(得分:0)

如果有人需要它:

timeout=5
timefile=/tmp/dc-time.info
if [[ ! -e $timefile ]]; then
    touch $timefile
fi
old=`stat $timefile --format=%Y`
touch $timefile
new=`stat $timefile --format=%Y`
count=$((timeout-new+old))
if [ $count -gt 0 ]
then
    echo "waiting..."
    sleep $count
fi