如何在使用python schedule modu与共享作业队列并行执行作业时传递参数

2024-05-29 08:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算并行运行多个作业,并使用作业队列遵循示例here,但它执行了一次,当我试图传递参数时,它引发了一个异常'NoneType' object is not callable。代码如下:

import Queue
import schedule
import threading
import time

def job(arg):
    print 'Argument is %s' % arg

def worker_main():
    while True:
        try:
            job_func = jobqueue.get()
            job_func()
        except Exception as e:
            print e

jobqueue = Queue.Queue()

schedule.every(2).seconds.do(jobqueue.put, job(1))
schedule.every(2).seconds.do(jobqueue.put, job(2))

worker_thread = threading.Thread(target=worker_main)
worker_thread.start()

while True:
    try:
        schedule.run_pending()
        time.sleep(1)
    except Exception as e:
        print e
        sys.exit()

输出为:

^{pr2}$

有什么办法解决这个问题吗?在


Tags: importtimequeueismaindef作业arg
1条回答
网友
1楼 · 发布于 2024-05-29 08:49:31

原因是传递给schedule.every(2).seconds.do(jobqueue.put, job(1))do方法的参数实际上是None。在

因为代码正在调用job函数并将1(和2)作为参数传递给job。因此,job函数的返回值(它是None,因为它只是打印)作为do方法调用的第二个参数。因此,作业队列中存储的不是函数引用,而是None实例。在

将参数传递给作业的问题是,schedule包中的do方法可以接受要运行的作业的额外参数,但正在计划的是将作业放入队列中,队列项只是没有额外参数的函数引用。在

一种解决方案是将作业与其参数一起放入队列。然后,工人需要获取它们并通过传递参数来调用作业。像这样:

import Queue
import schedule
import threading
import time

def job(arg):
    print 'Argument is %s' % arg

def worker_main():
    while True:
        try:
            job_func, job_args = jobqueue.get()
            job_func(*job_args)
        except Exception as e:
            print e

jobqueue = Queue.Queue()

schedule.every(2).seconds.do(jobqueue.put, (job, [1]))
schedule.every(2).seconds.do(jobqueue.put, (job, [2]))

worker_thread = threading.Thread(target=worker_main)
worker_thread.start()

while True:
    try:
        schedule.run_pending()
        time.sleep(1)
    except Exception as e:
        print e
        sys.exit()

这里我们将作业函数引用的元组和参数列表放入队列。 然后工人将获取它们,并将参数列表传递给job函数。在

另一种解决方案是将作业(job(1)job(2)调用)包装到其他不需要参数的函数中,然后将这些函数注册到作业队列中,如下所示:

^{pr2}$

相关问题 更多 >

    热门问题