有时候,我们想让程序在某个特定时间段内去多次执行某个任务,比如每天凌晨3点-4点,隔10秒执行一次任务,接下来,我们就用python自带的datetime模块和threading模块去实现它,代码如下:
import datetime
import threading
#任务描述:每天凌晨3-4点,隔10秒执行一次task任务
def func1():
'''凌晨3点开启任务'''
func2()
#如果需要每天都执行,加上下面两句
t = threading.Timer(86400,func1)
t.start()
def func2():
'''3点-4点,隔10秒执行一次任务task'''
task()
# 凌晨4点函数结束执行
now_time = datetime.datetime.now()
today_4 = datetime.datetime.strptime(str(datetime.datetime.now().year)+'-'+str(datetime.datetime.now().month)+'-'+str(datetime.datetime.now().day)+' '+'04:00:00','%Y-%m-%d %H:%M:%S')
#因为定时任务会延后10秒钟执行,所以设置终止条件时,需要提前10秒钟
if now_time <= today_4-datetime.timedelta(seconds=10):
t = threading.Timer(10, func2)
t.start()
def task():
'''需要执行的任务'''
print('task任务开始执行')
print('task任务执行完毕')
def main():
#获取当前时间
now_time = datetime.datetime.now()
#获取当前时间年、月、日
now_year = now_time.year
now_month = now_time.month
now_day = now_time.day
#今天凌晨3点时间表示
today_3 = datetime.datetime.strptime(str(now_year)+'-'+str(now_month)+'-'+str(now_day)+' '+'03:00:00','%Y-%m-%d %H:%M:%S')
#明天凌晨3点时间表示
tomorrow_3 = datetime.datetime.strptime(str(now_year)+'-'+str(now_month)+'-'+str(now_day)+' '+'03:00:00','%Y-%m-%d %H:%M:%S')
#判断当前时间是否过了今天凌晨3点,如果没过,则今天凌晨3点开始执行,过了则从明天凌晨3点开始执行,计算程序等待执行的时间
if now_time <= today_3:
wait_time = (today_3 - now_time).total_seconds()
else:
wait_time = (tomorrow_3 - now_time).total_seconds()
#等待wait_time秒后(今天凌晨3点或明天凌晨3点),开启线程去执行func函数
t = threading.Timer(wait_time,func1)
t.start()
if __name__ == '__main__':
main()如果想让程序更通用,可以将上述方法封装成一个定时器类,进行参数化
















