洗濯終了を通知する話 その5
さて、ここまでの4回でシステムの設置、プログラムの稼働が完了した。
いままでのあらすじ はこちら
あとはこれを常に動かしつつ、終了した後に再稼働するようにしなければならない。
ここで調べて出てきたのがcronである。
これは定期的にプログラムを起動してくれるものらしい。
時間を設定して定期的に再起動したり、ということに使用されるようだ。
今回はこれを利用して前回作成したPythonのプログラムを1分ごとに起動してもらうことにした。
まずはターミナルで以下を入力する
crontab -e
ちなみに、この編集の仕方は隣の『r』を押してcrontabを削除(remove)してしまう事故を誘発するため、あまり推奨されないらしい。
が、関係なくやっていく。
開くとこのような画面になるので、
# Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line # indicating with different fields when the task will be run # and what command to run for the task # # To define the time you can provide concrete values for # minute (m), hour (h), day of month (dom), month (mon), # and day of week (dow) or use '*' in these fields (for 'any'). # # Notice that tasks will be started based on the cron's system # daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command
一番下の行に以下を追加。
*/1 * * * * python3 /home/pi/wash_monitor.py
こうすることで、前回作成した洗濯完了通知プログラムが1分ごとに起動するようになる。
ところがこれでは不十分であることにすぐ気づいた。
このプログラムは、稼働していないときは即座にプログラムを終了するように組んである
が、稼働したときは、重複してプログラムが動いてしまうらしく、洗濯機が動いているときは1分毎に「洗濯を開始しました」という通知が来続ける事態に。
しかも重複して稼働した回数だけ、完了通知も届いてしまう。
これではなんのための通知だかわからないので、cronの内容を見直すことにした。
cronの重複起動防止については、様々な記事を参考にしたのだが、
https://www.t3a.jp/blog/web-develop/cron-multi-block/
https://digirakuda.org/blog/2018/03/27/post-139/
https://kitaeng.hateblo.jp/entry/2016/05/01/113114
どれを試してもいまいちうまく動かない。
ということで、こちらの記事のflock処理で多重起動を防止する形にした。
https://qiita.com/e_tyubo/items/af543ff4619e85a98c9a
稼働しているPythonファイルをロックファイルにし、それの有無をみて、ロックファイルがある場合は同じファイルを起動しない、という方法だ。
ちなみに、ロックファイルとは。
例えば共有フォルダに入れているExcelファイルを、同時に複数人が編集した際に
「他のユーザーが編集しているため上書きできません」
と出るあれのことらしい。
そういうわけで、crontabの先程の行に書いたのがこちら
*/1 * * * * flock -n /tmp/wash_monitor.lock python3 /home/pi/wash_monitor.py
コメント
コメントを投稿