1
1

More than 3 years have passed since last update.

Cron + Pythonの覚え書き

Posted at

cronの基本

編集方法と起動確認

$ sudo systemctl status cron
● cron.service - Regular background program processing daemon
     Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2021-02-13 19:03:03 JST; 3min 32s ago
       Docs: man:cron(8)
   Main PID: 352260 (cron)
      Tasks: 1 (limit: 9386)
     Memory: 436.0K
     CGroup: /system.slice/cron.service
             └─352260 /usr/sbin/cron -f

$ crontab -e

書式

分 時 日 月 曜 コマンドとなる

例 (シェルスクリプトの実行)

  • 毎日10時に実行
0 10 * * * test.sh
  • 毎月1日の0時0分に実行
0 0 1 * * test.sh
  • 1時間おきに実行(毎時0分)
* */1 * * * test.sh
  • 毎週土曜日の20時に実行
* 20 * * 6 test.sh

日曜日が0、土曜日が6と定義されており[0-6]の数値で指定する

適用

sudo systemctl restart cron

Pythonの実行

Pathの設定

 cronではパスの設定がされていないため、Pythonを絶対パスで指定するかPathを通す必要がある
 他のコマンドも同様であることを考えるとPathの設定をするのが無難
 crontab -eで編集モードに入り、最初の行に以下を追記する

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin

Python内で相対パスを使用している場合

 実行位置が違うため、カレントディレクトリを修正する必要がある。

サンプル

  • .envファイルを作成し、カレントディレクトリを記述する
CWD = '/home/hoge/hogehoge'
  • config.pyを作成し、環境変数の読み込みを行う
config.py
import os
from dotenv import find_dotenv, load_dotenv

load_dotenv(find_dotenv())
CWD = os.environ.get('CWD')
  • メインのファイルで config.pyを読み込み、環境変数を利用する
main.py
import os
import config

os.chdir(config.CWD)  # カレントディレクトリの変更
print(os.getcwd())    # カレントディレクトリの確認
1
1
1

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
1
1