在启动后60秒内重启服务的时间不要超过1次

时间:2018-10-04 09:41:43

标签: bash httpd.conf inotify

我有一个脚本,如果文件被更改,该脚本会重新启动httpd服务,如何实施速率控制以在60秒内仅一次重新启动服务

我知道该怎么做

将当前时间与修改log.txt的时间进行比较,但不知道如何开始

#!/bin/bash

mypidfile=/var/run/filewatch.pid

trap "rm -f $mypidfile" EXIT

echo $$ > "$mypidfile"


stdbuf -oL inotifywait -m /home/centos -r -e modify > log.txt |
    while read path action file >> log.txt; do
        if [[ "$file" =~ .*py$ ]] || [[ "$file" =~ .*css$ ]] || [[ "$file" =~ .*html$ ]] || [[ "$file" =~ .*js$ ]] ; then # Does the file end with .py css html js
            systemctl restart httpd # If so, do your thing here!
            #touch /home/centos/log.txt
            echo "test"
        fi
    done

2 个答案:

答案 0 :(得分:0)

  1. 记住上一次使用lasttime=$(date +%s)重新启动httpd的时间
  2. 如果触发了下一次重新启动,请睡到指定的时间,再减去上一次重新启动到现在的时间之差 difftime=$(($(date +%s) - lasttime)); if (( difftime < 60 )); then sleep $(( 60 - difftime )); fi; lasttime=$( ... )

像这样:

    if [[.... ]] ; then # Does the file end with .py css html js

        // delay up until 60 seconds from the last restart
        if [ -n "${lasttime:-}" ]; then
             difftime=$((60 - ($(date +%s) - lasttime)))
             if ((difftime > 0)); then
                  sleep "$difftime"
             fi
        fi
        lasttime=$(date +%s)

        systemctl restart httpd # If so, do your thing here!
        #touch /home/centos/log.txt
        echo "test"
    fi

答案 1 :(得分:0)

由于@Kamil Cuk的建议,我解决了这个问题:

inotifywait -m /home/centos -r -e modify |
    while read path action file>>log.txt; do
        if [[ "$file" =~ .*py$ ]] || [[ "$file" =~ .*css$ ]] || [[ "$file" =~ .*html$ ]] || [[ "$file" =~ .*js$ ]] ; then # Does the file end with .py css html js
           lastreboot=$(cat last_restart.txt)
           currenttime=$(date +%s)
           let elapsed=currenttime-lastreboot
           if [ "$elapsed" -lt 60 ]; then echo "less"
           else
           echo "restarting HTTPD"
           systemctl restart httpd
           echo $(date +%s)> last_restart.txt
           fi
        fi
    done