passing parameters to apscheduler handler function
Question:
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!
Answers:
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.
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")
Like Niel mention, with the current apscheduler you can use:
args (list|tuple) – list of positional arguments to call func with. See doc
Example:
sched.add_job(printit, args=[sometext], trigger='cron', minutes=2)
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!
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.
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")
Like Niel mention, with the current apscheduler you can use:
args (list|tuple) – list of positional arguments to call func with. See doc
Example:
sched.add_job(printit, args=[sometext], trigger='cron', minutes=2)