How can i pass parameters to schedule

Question:

How can I pass parameters to scheduler
Trying to use schedule with multiple parameters

cant figure it out


import time
import datetime as dt
from scheduler import Scheduler

schedule = Scheduler()

ItemName = "Crown"

Price = 5000

def SellItem(ItemName, Price):
    print(f"Item Name = {ItemName}n"
          f"Item Price = {Price}")

SellItem(ItemName, Price + 50000)

schedule.once(dt.timedelta(seconds=10), SellItem(ItemName, Price + 50000))
#Runs both instantly like normal and 10 seconds later Gives me a TypeError NoneType object is not callable


while True:
    schedule.exec_jobs()
    time.sleep(1)

Asked By: bro mo

||

Answers:

When scheduling a job, the scheduler expects a Callable as the handle parameter (the job you want executed) (see the documentation), however what SellItem(ItemName, Price + 50000) does is to actually call the function, and the argument passed to Scheduler.once is the what the function SellItem returns, which is nothing: None.
Hence, when trying to execute the job, you get the error you mention.

The code you’ve written is equivalent to

result = SellItem(ItemName, Price + 50000)
schedule.once(dt.timedelta(seconds=10), result)

If you want the scheduler to run your function, you need to give it your function as an argument:
schedule.once(dt.timedelta(seconds=10), SellItem).
Then, in order to provide arguments to the function SellItem when it is called, you can use the parameter args from the Scheduler.once function, as mentioned in the documentation, here
So, with your code that would be:

import time
import datetime as dt
from scheduler import Scheduler

schedule = Scheduler()

ItemName = "Crown"

Price = 5000

def SellItem(ItemName, Price):
    print(f"Item Name = {ItemName}n"
          f"Item Price = {Price}")

schedule.once(dt.timedelta(seconds=10), SellItem, args=(ItemName, Price + 50000))


while True:
    schedule.exec_jobs()
    time.sleep(1)

Also, as a side note, you should try to follow PEP8 recommendations regarding naming conventions for your variables and functions

Answered By: Florent MONIN
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.