如何在 python 中使用 schedule 模块调用方法?

How to call methods using schedule module in python?

我们可以像这样使用 schedule 调用一个简单的函数

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()

但是当我创建一个 class 并调用一个方法时

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()

我得到

TypeError: the first argument must be callable

alarm.wake_up()替换为alarm.wake_up

当你加上括号的时候,实际上是调用并执行了方法wake_up。但是,当您只是执行 alarm.wake_up 时,它会创建对该方法的引用,这正是 schedule 模块想要的。

更改在第 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()