python的sched定时任务

主要参考了这一篇:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值