メモリリークなんて考えたことなかった。
以前書いたコードをラズパイでは知らせてたらメモリエラーが出てきてだめになりました。ガーベージコレクションgc.collect()
じゃ対応しきれていなかったので、OSに標準搭載の定時実行機能を利用したよ、という話。
全体としては、「毎7分に起動して、色々読み込んでもらって、毎0分に指定のことを実行してもらう」みたいな処理にした。
対策1:OS(RasberryPiOS)標準搭載の定時実行機能の利用
crontab -e
# nano editorの選択
1
# 以下のものを追記
# 分 時 日 月 曜日 コマンド
7,17,27,37,47,57 * * * * python /home/pi/Desktop/abcdefg.py
# 保存
Ctrl + O
# 決定
Enter
# 終了
Ctrl + X
# 確認
crontab -l
対策2:実行したら抜けるためのコードを追加
別にimport sys
しなくてもエラー起きて落ちてくれると思うんだけど一応入れたほうがいいかな。
def minute_interval(interval_min: int, at_sec: int, function, *args, **kwargs):
"""RUNS FUNCTION REPETITIVELY
Args:
interval_min(int) : Value of minute. If 11, it will operate at 00, 11, 22, 33, 44, and 55.
at_sec(int) : Value of second. If 5, it will operate at 05.
function: Function you want to call repetitively
"""
while True:
now = datetime.now()
# when interval_min is 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, or 30
if now.minute + interval_min < 60:
wait_min = -now.minute % interval_min
# when interval_min CANNOT divide 60. e.g: 7,8,9,11,13...
else:
wait_min = 60 - now.minute
now_sec = now.second + (now.microsecond / 1000_000)
wait_sec = ((wait_min * 60) + (at_sec - now_sec)) % (interval_min * 60)
print(f'call func after {int(wait_sec/60)} min {wait_sec%60} sec')
time.sleep(wait_sec)
function(*args, **kwargs)
sys.exit(0)