LoginSignup
0
1

More than 1 year has passed since last update.

残プロ 第-15回 ~cronでpythonを定時実行する~

Posted at

第-11回のコード

以下のように書くと毎日午前7時に定期実行でした.

0 7 * * * python3 /home/pi/Documents/hello.py
# 書き方は[分 時 日 月 年 コマンド]

これを7, 16時に実行するように変えていきたいと思います.

/nで毎nごとに実行

単純に1行増やしてもいいのですが,せっかくなので少し別の方法を試します.

1.まず,crontabに1時間ごとに実行として登録.

0 /1 * * * python3 /home/pi/Documents/hello.py
# 書き方は[分 時 日 月 年 コマンド]

main関数

2.main関数を定義して時間で条件処理

先日,コメントから「main関数使うといいよ~」と教えてもらったので,せっかくですし使ってみます.

import datetime

def main():
    print(datetime.datetime.now().hour)


if __name__ == '__main__':
    if datetime.datetime.now().hour in [7, 16]:
        main()

in演算子を使いました.リストに含まれた場合はmain関数実行となります.

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