繁体   English   中英

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

[英]How to pass arguments when execute jobs in parallel with a shared job queue using python schedule module

我打算并行运行多个作业,并使用作业队列遵循此处的示例,但它执行一次并引发异常'NoneType' object is not callable在我尝试传递参数时'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()

输出是:

Arg is 1
Arg is 2
'NoneType' object is not callable
'NoneType' object is not callable
'NoneType' object is not callable
'NoneType' object is not callable
'NoneType' object is not callable
'NoneType' object is not callable
...

有什么想法可以解决这个问题吗?

原因是在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(1)job(2)调用)包装在其他不需要参数的函数中,然后将这些函数注册到作业队列,如下所示:

def job1():
    job(1)

def job2():
    job(2)

jobqueue = Queue.Queue()

schedule.every(2).seconds.do(jobqueue.put, job1)
schedule.every(2).seconds.do(jobqueue.put, job2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM