21

How can I pass parameters to schedule?

The function I want to get called:

def job(param1, param2):
    print(str(param1) + str(param2))

How I schedule it:

schedule.every(10).minutes.do(job)

How can I pass a parameter to do(job)?

2 Answers 2

39

In general with this kind of thing you can always do this:

schedule.every(10).minutes.do(lambda: job('Hello ', 'world!'))

Looking at the source:

def do(self, job_func, *args, **kwargs):
    """Specifies the job_func that should be called every time the
    job runs.
    Any additional arguments are passed on to job_func when
    the job runs.
    :param job_func: The function to be scheduled
    :return: The invoked job instance
    """
    self.job_func = functools.partial(job_func, *args, **kwargs)

We see that you can also do this:

schedule.every(10).minutes.do(job, 'Hello ', 'world!')

Or, as the code suggests, an alternative to the generic lambda method is:

schedule.every(10).minutes.do(functools.partial(job, 'Hello ', 'world!'))
4
  • Thank you for your help. I am new to use lamda function, can you tell me how to use it and when to use it ? I used do(job(param1, param2)) but It was error. What the different between do(job(param1, param2)) and do(lambda: job('Hello ', 'world!')) ? Thanks Dec 1, 2016 at 6:12
  • 1
    lambda: ... returns a function with no arguments, similar to def function_name(): return ... but it lets you make the code a bit shorter. do(job(param1, param2)) simply calls job(param1, param2) immediately and passes the result to do which makes no sense.
    – Alex Hall
    Dec 1, 2016 at 7:56
  • is it like return a void function in Java or C# ? so it does not return anything ? Dec 1, 2016 at 8:59
  • 1
    No, it returns the expression after the :. Google "python lambda" and do some reading.
    – Alex Hall
    Dec 1, 2016 at 9:03
1
schedule.every(10).minutes.do(job, 'do something', 'like this')

My friend tried the above syntax but it didn't work, so if it does not work you can use

schedule.every(10).minutes.do(job('do something', 'like this'))

His schedule statement was not like this exactly it was like this -

schedule.every().monday.at('8:30')do(job('It was', 'like this'))
1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.