Last active
August 5, 2020 17:40
-
-
Save draganHR/97d4d64aff1817ba218a to your computer and use it in GitHub Desktop.
Example of django command using multiprocessing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from time import sleep | |
from multiprocessing import Process | |
from django.core.management.base import BaseCommand, CommandError | |
logger = logging.getLogger(__name__) | |
class Command(BaseCommand): | |
option_list = BaseCommand.option_list | |
subcommands = ('foo', 'bar', 'baz') | |
def handle(self, subcommand=None, *args, **options): | |
status = 'example' | |
if not subcommand: | |
procs = [] | |
for task in self.subcommands: | |
proc = Process(target=getattr(self, 'handle_%s' % task), | |
name='indexer-%s' % task, | |
kwargs={'status': status} | |
) | |
proc.start() | |
procs.append(proc) | |
for proc in procs: | |
proc.join() | |
elif subcommand in self.subcommands: | |
getattr(self, 'handle_%s' % subcommand)(status) | |
else: | |
raise CommandError('Invalid argument: %r' % subcommand) | |
def handle_foo(self, status): | |
for i in range(5): | |
print 'foo', i, status | |
sleep(1) | |
def handle_bar(self, status): | |
for i in range(8): | |
print 'bar', i, status | |
sleep(1.2) | |
def handle_baz(self, status): | |
for i in range(3): | |
print 'baz', i, status | |
sleep(1.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment