编写 Bash 脚本以在特定时间运行和结束

编写 Bash 脚本以在特定时间运行和结束

我想创建一个脚本来执行以下操作。从一天中的给定时间开始,在另一个给定时间结束。

例如,我有一个想要测试的程序,因此我的脚本将设置为在晚上 10:00 开始,并继续运行到上午 9:00。

这是我关于一次又一次运行程序的另一个问题的延续。

我有以下内容:

#!/bin/bash

trap "echo manual abort; exit 1"  1 2 3 15;
RUNS=0;
while open  -W /Path/to/Program.app
do
    RUNS=$((RUNS+1));
    echo $RUNS > /temp/autotest_run_count.txt;
done

exit 0

该脚本本质上运行我的程序(在 Mac OSX 中)并捕获任何故障,否则它将在程序关闭时重新运行该程序。

我希望能够像上面提到的那样运行它。晚上 10:00 开始。上午 9:00 结束。

你的建议总是有用的。

谢谢!

尤登

答案1

我已经扩展了你的脚本,这样你就可以在启动时运行它一次,它就会在晚上 9 点到上午 9 点之间完成它的工作。

#!/bin/bash -·
LOGFILE="/tmp/autotest_run_count.txt"

trap "echo manual abort; exit 1"  1 2 3 15
RUNS=0
while [ 1 ] ; do·
    HOUR="$(date +'%H')"
    if [ $HOUR -ge 21 -a $HOUR -lt 9 ] ; then
        # run program
        libreoffice || exit 1
        RUNS=$((RUNS+9))
        echo $RUNS > $LOGFILE
    else
        echo $RUNS, waiting H=$HOUR > $LOGFILE
        # note: calculating the time till next wakeup would be more 
        # efficient, but would not work when the time changes abruptly
        # e.g. a laptop is suspended and resumed
        # so, waiting a minute is reasonably efficient and robust
        sleep 60
    fi
done

答案2

我使用这个脚本。它在给定时间启动另一个脚本,并在另一个给定时间停止它。在这期间,它会定期检查脚本是否仍在运行,如果没有,则重新启动它。您只需根据需要更改开始时间、停止时间、脚本名称和正在使用的 shell,并注释掉相关的“while”行(日期+时间或仅时间)。

    #!/bin/bash

    if [ "$1" = "go" ]; then

        starttime1=0900 #e.g. 201712312355 for date+time or 1530 for time
        stoptime1=1100
        scriptname1="./myscript"

        # wait for starttime
        echo "Waiting for " "$starttime1" " to start " "$scriptname1";
        #while [ $(($(date +"%Y%m%d%H%M") < $starttime1)) = 1 ]; do #day and time
        while [ $((10#$(date +"%H%M") != 10#$starttime1)) = 1 ]; do #just time. 10# forces following number to be interpreted as base 10. Otherwise numbers with leading zero will be interpreted as octal and this causes errors.
            sleep 10;
        done;

        # run target script
        lxterminal -e "$scriptname1";

        # check if the target script is running, until the stoptime is reached and restart it if necessary
        echo "Waiting for " "$stoptime1" " to stop " "$scriptname1";
        #while [ $(($(date +"%Y%m%d%H%M")<$stoptime1)) = 1 ]; do #day and time
        while [ $((10#$(date +"%H%M") != 10#$stoptime1)) = 1 ]; do #just time. 10# forces following number to be interpreted as base 10. Otherwise numbers with leading zero will be interpreted as octal and this causes errors.
            sleep 10;
            if [ -z $(pidof -x "$scriptname1") ]; then
                echo "script was stopped.";
                lxterminal -e "$scriptname1";
            fi;
        done;

        # end the target script when the stoptime is reached
        kill $(pidof -x "$scriptname1");
        echo "ok.";

    else
        lxterminal -e "$0" go;
        exit;
    fi

相关内容