LoginSignup
7
5

More than 5 years have passed since last update.

djangoコマンドの二重起動を防止する

Posted at

djangoコマンドとは'python manage.py 〜'で実行するコマンドのことです。
デフォルトでshellなどたくさん便利なコマンドが用意されています。
ここでは詳しく説明しませんがカスタムコマンドをつくることが可能です。
そして、そのカスタムコマンドなどはcrontabなどバッチとして動かすことが多いのですが、なんらかの原因で二重起動しないようにしてみます。

custom_command.py
import sys
import commands
from django.core.management.base import BaseCommand

def is_process_exist(process_name):
    """
    このプロセスが動いていたらTrueを返す
    """
    output = commands.getoutput("ps -ef | grep '%s' | grep -v grep | wc -l" % (process_name))
    is_exist = int(output) >= 2

    return is_exist


class Command(BaseCommand):
    def handle(self, *args, **options):
        # 二重起動チェック
        if is_process_exist(__name__.split('.')[-1]):
            sys.exit('duplication!')

        # 以下処理〜

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