【问题标题】:How to stop django management command after a time period using multiprocessing?如何在使用多处理一段时间后停止 django 管理命令?
【发布时间】:2022-02-01 22:41:13
【问题描述】:

我必须按以下方式运行 python 命令函数:

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

此代码为库函数提供参数,该函数又返回所需的输出。 我想在运行 100 秒 后停止此命令功能。如何使用 multiprocessing 将库函数作为进程调用并在 100 秒内终止程序?

【问题讨论】:

    标签: python django time multiprocessing


    【解决方案1】:

    我查看了multiprocessing docs 并想出了这个:

    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
    

    我也没有测试过。

    【讨论】:

    • 我已经编辑了代码。未定义的变量是我的错误
    • @AyushSinha - 更新以反映您的更改
    • 库类'func'的对象不能直接在函数do_da_thing()中使用
    • @AyushSinha - 那是你的代码......我从你的代码中复制过来。我不知道func.library_function 是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2021-12-30
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多