Djangoでcron

Yuji Yamasaki
Nov 6 · 3 min read

Djangoで行っているシステム開発で,1日に1回定期処理をさせる必要が出た.

要件

1日の終わりに,1日中取得し続けているデータの処理を行う.

もちろん

pythonで適当にコードを作って直接MySQLを叩いてそれをcronで定期実行させればいいが

モデルの定義などはDjangoに入っているので,出来ればそれを利用したい

ただDjangoってWebフレームワークだし,その内のファイル1つだけ実行させるとか可能か?

といったことを解決した備忘録

選んだ方法

Djangoの新しいコマンドを定義すれば良さそう

というのも

Djangoはある程度コマンドが用意されてる

$ python3 manage.py runserver
$ python3 manage.py migrate
$ python3 manage.py makemigrations
...

これを新しく定義してcronで叩くことにした.

手順

新しいアプリケーションを作成

$ python3 manage.py startapp cron

正直既存のアプリケーションの中にコマンドの定義をしてもいいが分かりやすくするためにこうした

settings.pyに作成したアプリケーションを追加

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cron', #これ
]

作成したアプリケーションにmanagementディレクトリ追加

$ cd cron
$ mkdir cron/management

managementディレクトリの下にcommandsディレクトリ追加

$ cd management
$ mkdir commands

commandsディレクトリの下にcron.pyを追加

$ cd management
$ vim cron.py

このcron.pyはコマンドの名前となるので,コマンドの名前をsqlにしたければsql.pyを作成すれば良い

cron.pyを編集

from django.core.management.base import BaseCommand

class Command(BaseCommand):
def handle(self, *args, **options):
for i in range(100):
print('Hello Medium! ', end='')

本来はモデルをインポートして処理させるが諸般の事情で割愛
引数を強制することも可能

実行

$ python3 manage.py cron

cronで定期実行の設定

$ crontab -e0 5 * * * /usr/local/bin/python3 /home/moyashi/mon/manage.py cron

今回は毎日朝5時に指定

おわりに

今回は比較的すんなり解決

    Yuji Yamasaki

    Written by

    I have insomnia.

    inet-lab

    inet-lab

    inet-lab blog

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade