I have to run a python command function in the following manner:
from django.core.management import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('plant', type=int)
parser.add_argument('month', type=int)
def handle(self,*args,**options):
func= Library_Class()
plants= options.get('plant')
month= options.get('month')
for plant in plants:
result= func.library_function(plant,month)
return
This code gives arguments to the library function which in turn returns the required output. I want to stop this command function after 100 seconds of run time. How Do I use multiprocessing to call the library function as a process and terminate the program in 100 seconds?
I looked at the multiprocessing docs and came up with this:
from multiprocessing import Pool, TimeoutError
from django.core.management import BaseCommand
def do_da_thing(plants, month):
for plant in plants:
result= func.library_function(plant, month)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('plant', type=int)
parser.add_argument('month', type=int)
def handle(self,*args,**options):
func= Library_Class()
plants= options.get('plant')
date= options.get('month')
with Pool(processes=1) as pool:
res = pool.apply_async(do_da_thing, (plants, month))
try:
# block for 100 sec or until we get a reply
result = res.get(timeout=100)
except TimeoutError:
self.stdout.write("took longer than 100 seconds")
return
I also haven't tested it at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.