我有一个函数,它每分钟从交换中获取和存储一些东西。我使用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中的一个bug吗?还是我做错了什么?
欢迎所有提示!
这让我很恼火,直到我终于弄明白了。所以,在潜伏了年之后,我创建了一个stackoverflow帐户。第一个帖子!
试着去掉lambda (I know…(我也走了这条路),并通过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
这对我有用:
for apiCall in apiCalls:
print 'Start cron for: ', apiCall
action = lambda x = apiCall: getAndStore(x)
apsched.add_cron_job(action , minute='0-59')