Search code examples
pythonoopschedule

How to call methods using schedule module in python?


we can call a simple function using schedule like this

import schedule
def wake_up():
    print("Wake Up! It's 8:00")
schedule.every().day.at("08:00").do(wake_up)
while True:
    schedule.run_pending()

but when im creating a class and calling a method

import schedule
class Alarm():
    def wake_up(self):
        print("Wake Up!")
alarm=Alarm()
schedule.every().day.at("08:00").do(alarm.wake_up())
while True:
    schedule.run_pending()

i get

TypeError: the first argument must be callable

Solution

  • Replace alarm.wake_up() with alarm.wake_up.

    When you add the parenthesis, you actually call and execute the method wake_up. However, when you just do alarm.wake_up, it creates a reference to that method instead, which is what the schedule module wants.

    Change is on line 7:

    import schedule
    class Alarm():
        def wake_up(self):
            print("Wake Up!")
    
    alarm=Alarm()
    schedule.every().day.at("08:00").do(alarm.wake_up)
    
    while True:
        schedule.run_pending()