主要参考了这一篇:
https://www.cnblogs.com/wang1122/p/6709148.html
简洁明了一些写吧。
首先,要引入的模块是:
import sched
import time
from datetime import datetime
其次,想要定时的任务是:
def printTime():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
然后,为了实现定时,将需要用到的定时器对象初始化为:
schedule = sched.scheduler(time.time, time.sleep)
将定时任务放入定时器中:
schedule.enter(0, 0, printTime, (1,))
'''
schedule.enter(delay, priority, action, arguments)
其中:
delay:延迟执行任务的时间,为0表示立即执行任务
priority:执行任务的优先级,0为最大,1234依次降低
action:执行任务的函数名,这里是printTime
arguments:执行任务的函数参数,格式为 (arg1,arg2,...,) 最后一定要有逗号,没有参数就是()
'''
执行任务:
schedule.run()
但是这样任务只能执行一次,为了能够循环定时,改造一下函数,每次在函数执行完成之后,重新将函数放入定时器:
def printTime(timeInterval):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
schedule.enter(timeInterval, 0, printTime, (timeInterval,))
最后成品:
import sched
import time
from datetime import datetime
schedule = sched.scheduler(time.time, time.sleep)
def printTime(timeInterval):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
schedule.enter(timeInterval, 0, printTime, (timeInterval,))
if __name__ == "__main__":
schedule.enter(0, 0, printTime, (5,))
schedule.run()