Python Apscheduler cron job from loop并不执行所有不同的版本

2024-09-27 09:26:10 发布

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

我有一个函数,它每分钟都能从交换机获取和存储数据。我使用(通常非常出色)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')

这很好,但由于我是一名程序员,而且我喜欢自动化,所以我会这样做:

^{pr2}$

运行此程序时,输出如下:

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

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

欢迎所有提示!在


Tags: 数据lambda函数addfor作业jobstart
2条回答

这对我很有效:

for apiCall in apiCalls:

    print 'Start cron for: ', apiCall

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

这让我很恼火,直到我终于弄明白了。所以,我在潜伏了多年之后,创建了一个stackoverflow账户。第一个帖子!在

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

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)

输出为:

^{pr2}$

相关问题 更多 >

    热门问题