簡體   English   中英

如何在使用多處理一段時間后停止 django 管理命令?

[英]How to stop django management command after a time period using multiprocessing?

我必須以下列方式運行 python 命令 function :

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

此代碼將 arguments 提供給庫 function,后者又返回所需的 output。 我想在運行100 秒后停止這個命令 function 。 如何使用多處理將庫 function 作為進程調用並在 100 秒內終止程序?

我查看了多處理文檔並想出了這個:

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

我也完全沒有測試過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM