Python实现每日凌晨3点定时执行任务的方法

Jasper
Jasper
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍在Python中利用threading模块实现每天凌晨3点自动执行指定功能的方法。通过计算当前时间与次日3点的时间差,使用Timer设置延迟启动,并在任务函数内部递归调用自身以实现循环执行,从而完成周期性定时任务的配置。

具体实现代码如下所示:

'''
Created on 2018-4-20

例子:每天凌晨3点执行func方法
'''
import datetime
import threading

def func():
  print("haha")
  #如果需要循环调用,就要添加以下方法
  timer = threading.Timer(86400, func)
  timer.start()

# 获取现在时间
now_time = datetime.datetime.now()
# 获取明天时间
next_time = now_time + datetime.timedelta(days=+1)
next_year = next_time.date().year
next_month = next_time.date().month
next_day = next_time.date().day
# 获取明天3点时间
next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 03:00:00", "%Y-%m-%d %H:%M:%S")
# # 获取昨天时间
# last_time = now_time + datetime.timedelta(days=-1)

# 获取距离明天3点时间,单位为秒
timer_start_time = (next_time - now_time).total_seconds()
print(timer_start_time)
# 54186.75975


#定时器,参数为(多少时间后执行,单位为秒,执行的方法)
timer = threading.Timer(timer_start_time, func)
timer.start()

上述关于Python定时器实现每天凌晨3点执行的内容即为本文分享的全部信息,旨在为读者提供参考。若觉得有用,欢迎支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表