LoginSignup
6
13

More than 3 years have passed since last update.

Pythonでcronライクにジョブを定期実行させる

Posted at

pythonでタスクキューを実現するライブラリにhueyというものがあります。同じタスクキューのライブラリで有名なceleryに比べてシンプルにジョブの定期実行を実装できます。
なお今回は通常のタスク実行には触れません。

事前準備

  • ライブラリのインストール
pip install huey
pip install redis
  • ブローカーに使うRedisの起動

お手軽にdockerで起動しておきます

docker run --rm -d -p 6379:6379 redis

タスクを記述

今回はブローカーにRedisを起動したためRedisHueyを呼び出します。
関数にperiodic_taskのデコレータをつけるだけで定期実行ジョブを登録することができます。

main.py
from huey import RedisHuey, crontab
import time

huey = RedisHuey(host="127.0.0.1")


@huey.periodic_task(crontab(minute="*"))
def test():
    print("process start")
    time.sleep(5)
    print("process end")

デコレータの引数として与えたcrontabでジョブの実行時間を指定します。今回は毎分です。

Wokerを起動

hueyをインストールするとhuey_consumerというコマンドが使えるようになるのでこれでworkerプロセスを起動します。

$ huey_consumer main.huey

[2020-07-16 23:18:59,827] INFO:huey.consumer:MainThread:Huey consumer started with 1 thread, PID 2744 at 2020-07-16 14:18:59.827805
[2020-07-16 23:18:59,828] INFO:huey.consumer:MainThread:Scheduler runs every 1 second(s).
[2020-07-16 23:18:59,828] INFO:huey.consumer:MainThread:Periodic tasks are enabled.
[2020-07-16 23:18:59,828] INFO:huey.consumer:MainThread:The following commands are available:
+ main.test
[2020-07-16 23:18:59,836] INFO:huey.consumer.Scheduler:Scheduler:Enqueueing periodic task main.test: 30a61be7-903c-4fa7-815f-c5c013074085.
[2020-07-16 23:18:59,841] INFO:huey:Worker-1:Executing main.test: 30a61be7-903c-4fa7-815f-c5c013074085
process start
process end
[2020-07-16 23:19:04,847] INFO:huey:Worker-1:main.test: 30a61be7-903c-4fa7-815f-c5c013074085 executed in 5.005s
[2020-07-16 23:19:59,830] INFO:huey.consumer.Scheduler:Scheduler:Enqueueing periodic task main.test: 8166b273-1b97-427a-a349-a2772ea67fd2.
[2020-07-16 23:19:59,834] INFO:huey:Worker-1:Executing main.test: 8166b273-1b97-427a-a349-a2772ea67fd2
process start
process end
[2020-07-16 23:20:04,839] INFO:huey:Worker-1:main.test: 8166b273-1b97-427a-a349-a2772ea67fd2 executed in 5.005s

1分ごとにジョブが実行されているのが確認できます。

以上

6
13
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
6
13