来自循环的Python Apscheduler cron作业不会执行所有不同的版本

时间:2014-06-27 13:59:06

标签: python cron apscheduler

我有一个功能,可以每分钟从交易所获取和存储一些东西。我使用(通常很好的)APScheduler运行函数。不幸的是,当我从循环中添加cron作业时,它似乎并没有像我期望的那样工作。

我有一个带有几个字符串的小列表,我想为其运行getAndStore函数。我可以这样做:

from apscheduler.scheduler import Scheduler
apsched = Scheduler()
apsched.start()
apsched.add_cron_job(lambda: getAndStore('A'), minute='0-59')
apsched.add_cron_job(lambda: getAndStore('B'), minute='0-59')
apsched.add_cron_job(lambda: getAndStore('C'), minute='0-59')

这很好用,但由于我是程序员,我喜欢自动化东西,我这样做:

from apscheduler.scheduler import Scheduler
def getAndStore(apiCall):
    # does a call to the api using apiCall as a value
    # and stores it in the DB.
    print apiCall

apiCalls = ['A', 'B', 'C']

apsched = Scheduler()
apsched.start()
for apiCall in apiCalls:
    print 'Start cron for: ', apiCall
    apsched.add_cron_job(lambda: getAndStore(apiCall), minute='0-59')

当我运行它时,输出如下:

Start cron for:  A
Start cron for:  B
Start cron for:  C
C
C
C

奇怪的是它似乎是为A,B和C启动它,但它实际上为C启动了三次cron。这是APScheduler中的错误吗?或者我在这里做错了什么?

欢迎所有提示!

2 个答案:

答案 0 :(得分:2)

这让我生气了一段时间,直到我终于明白了。所以,我在潜伏的之后创建了一个stackoverflow帐户。第一篇文章!

尝试删除lambda(我知道......,我也沿着那条路走下去)并通过args传递参数作为元组。我在下面使用了稍微不同的调度程序,但它应该很容易适应。

from apscheduler.schedulers.background import BackgroundScheduler
import time   

def getAndStore(apiCall):
    # does a call to the api using apiCall as a value
    # and stores it in the DB.
    print(apiCall)

apiCalls = ['A', 'B', 'C']

apsched = BackgroundScheduler()
apsched.start()
for apiCall in apiCalls:
    print ('Start cron for: ' + apiCall)
    apsched.add_job(getAndStore, args=(apiCall,), trigger='interval', seconds=1)

# to test
while True:
    time.sleep(2)

输出是:

Start cron for: A
Start cron for: B
Start cron for: C
B
A
C

答案 1 :(得分:-1)

这对我有用:

for apiCall in apiCalls:

    print 'Start cron for: ', apiCall

    action = lambda x = apiCall: getAndStore(x)
    apsched.add_cron_job(action , minute='0-59')