首页 > 解决方案 > 如何使 APScheduler ProcessPoolExecutor 在完成后关闭进程并仅生成它需要的进程?

问题描述

ProcessPoolExecutor 产生了一堆处理 apscheduler 作业的进程。我希望 ProcessPoolExecutor 生成的进程在成功完成作业后实际关闭,并为下一次执行所述作业生成一个新进程。如果不需要,我也希望不会产生进程。然而这不会发生。如果我将 max workers 设置为 10,将产生 10 个进程。即使唯一的作业的 max_instances 为 3。在其中一个进程完成作业后,该进程不会被回收,而只是重新用于下一次运行所述作业。

我举个例子:

创建一个利用 BlockingScheduler 并使用 ProcessPoolExecutor 作为其执行器的 apscheduler。

def printing_job():
    print("print this...")

def main():
    executors = {
        'default': ProcessPoolExecutor(max_workers=10)
    }
    job_defaults = {
        'coalesce': False,
        'max_instances': 3,
        'misfire_grace_time': None
    }
    scheduler = BlockingScheduler(executors=executors,
                                  daemonic=True,
                                  daemon=True)
    scheduler.add_job(printing_job, 'interval', seconds=1)
    scheduler.start()

产生了 11 个进程,10 个调度程序进程和主进程:

user   61428  59435 18 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61456  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61457  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61458  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61459  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61460  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61461  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61462  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61463  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61464  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py
user   61465  61428  0 16:25 pts/2    00:00:00 ../bin/python3 ./test.py

工作只使用了 3 个。我应该最多看到 4 个进程。应该收获和重新创建这些过程。

APScheduler 无法实现这种范式吗?

ProcessPoolExecutor 声明 max_workers 是最多生成的工人。关键词最多是,对我来说,这表明它不应该产生超过它需要的数量。

标签: pythonapscheduler

解决方案


我通过自定义函数来概括我想要执行的并行和/或并发进程的类型或多或少地解决了这个问题。在该函数中,您可以执行您希望在此处执行的相同操作。我无法以任何其他方式解决这个问题。


推荐阅读