1

我有一个功能,可以每分钟从交易所获取和存储一些东西。我使用(通常非常出色)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 启动了 3 次 cron。这是 APScheduler 中的错误吗?还是我在这里做错了什么?

欢迎所有提示!

4

2 回答 2

3

这让我烦恼了一段时间,直到我终于弄明白了。这么多,经过多年的潜伏,我创建了一个 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
于 2015-03-12T16:12:39.030 回答
-1

这对我有用:

for apiCall in apiCalls:

    print 'Start cron for: ', apiCall

    action = lambda x = apiCall: getAndStore(x)
    apsched.add_cron_job(action , minute='0-59')
于 2015-07-18T05:23:23.067 回答