在Python中,可以使用threading模块中的Timer类来创建一个简单的计时器,或者使用schedule库来实现复杂的定时任务。
使用threading.Timer创建一个简单的计时器:
import threading
def print_message(message, seconds):
timer = threading.Timer(seconds, print, args=[message])
timer.start()
print_message("Hello, World!", 5)使用schedule库实现复杂的定时任务:
首先需要安装schedule库,可以使用pip安装:
pip install schedule然后,可以使用以下代码实现定时任务:
import schedule
import time
def job():
print("I'm working...")
# 每5秒运行一次
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)schedule库提供了丰富的API来设置不同的时间间隔,例如:每分钟、每小时等,使得定时任务的设置更加灵活。