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!

Asked By: still.Learning

||

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.

Answered By: Ali Afshar

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")
Answered By: Niel

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)

Answered By: aldwip34
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.