Skip to content

Instantly share code, notes, and snippets.

@jeromecc
Forked from kkirsanov/multitask.py
Created December 6, 2020 22:18
Show Gist options
  • Save jeromecc/3a7dd1b7a1988fcc02e83d636d08611a to your computer and use it in GitHub Desktop.
Save jeromecc/3a7dd1b7a1988fcc02e83d636d08611a to your computer and use it in GitHub Desktop.
run multiple django managememnt commands simultaneously
# coding=utf8
import logging
import threading
import time
from django.core.management import call_command
from django.core.management.base import BaseCommand
logger = logging.getLogger('multirunner')
class CommandRunner(threading.Thread):
def __init__(self, command, args):
threading.Thread.__init__(self)
self.command = command
self.args = args
self.stop_command = threading.Event()
def run(self):
while not self.stop_command.is_set():
try:
call_command(self.command, *self.args)
except Exception as e:
logging.error(e)
time.sleep(1)
def stop(self):
self.stop_command.set()
class MultiTask:
def __init__(self, tasks):
self.threads = []
for task, args in tasks:
self.threads.append(CommandRunner(task, args))
def start(self):
for t in self.threads:
t.start()
def stop(self):
for t in self.threads:
t.stop()
class Command(BaseCommand):
def handle(self, *args, **options):
tasks = [('t1', ['param1']), ('t1', ['param2'])]
mt = MultiTask(tasks)
mt.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment