X秒ごとにコマンドを実行する

X秒ごとにコマンドを実行する

10秒ごとにコマンドを実行し、バックグラウンドで実行するようにしたい(したがってwatch?を削除します)。すべての回答は次のように表示されますが、実行には11〜14秒かかります。これはどのように達成できますか?

while true; do
    # perform command that takes between 1 and 4 seconds
    sleep 10
done

ベストアンサー1

どうですか?

( # In a subshell, for isolation, protecting $!
  while true; do
    perform-command & # in the background
    sleep 10 ;
    ### If you want to wait for a perform-command
    ### that happens to run for more than ten seconds,
    ### uncomment the following line:
    # wait $! ;
    ### If you prefer to kill a perform-command
    ### that happens to run for more than ten seconds,
    ### uncomment the following line instead:
    # kill $! ;
    ### (If you prefer to ignore it, uncomment neither.)
  done
)

ETA:追加の保護のためのこれらの説明、代替案、およびサブシェルを含めると、初めて起動したときよりもはるかに複雑に見えます。比較のために、waitorkillおよびそれらの分離要件について心配する$!前の外観は次のとおりです。

while true; do perform-command & sleep 10 ; done

残りは必要なときにすぐそこにあります。

おすすめ記事