passing parameters to apscheduler handler function

2020-06-30 05:16发布

I am using apscheduler and I am trying to pass in parameters to the handler function that gets called when the scheduled job is launched:

from apscheduler.scheduler import Scheduler
import time

def printit(sometext):
    print "this happens every 5 seconds"
    print sometext

sched = Scheduler()
sched.start()

sometext = "this is a passed message"
sched.add_cron_job(printit(sometext), second="*/5")

while True:
    time.sleep(1)

Doing this gives me the following error:

TypeError: func must be callable

Is it possible to pass parameters into the function handler. If not, are there any alternatives? Basically, I need each scheduled job to return a string that I pass in when I create the schedule. Thanks!

标签: python
2条回答
可以哭但决不认输i
2楼-- · 2020-06-30 06:03

printit(sometext) is not a callable, it is the result of the call.

You can use:

lambda: printit(sometext)

Which is a callable to be called later which will probably do what you want.

查看更多
家丑人穷心不美
3楼-- · 2020-06-30 06:03

Since this is the first result I found when having the same problem, I'm adding an updated answer:

According to the docs for the current apscheduler (v3.3.0) you can pass along the function arguments in the add_job() function.

So in the case of OP it would be:

sched.add_job(printit, "cron", [sometext], second="*/5")
查看更多
登录 后发表回答