0
1

More than 3 years have passed since last update.

RaspberryPiでメモリリークに対応した話

Last updated at Posted at 2020-08-27

メモリリークなんて考えたことなかった。

以前書いたコードをラズパイでは知らせてたらメモリエラーが出てきてだめになりました。ガーベージコレクション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)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1