import datetime,threading
def fun_timer():
print('hello timer') # 打印输出
global timer # 定义变量
timer = threading.Timer(5, fun_timer) # 5秒调用一次函数
# 定时器构造函数主要有2个参数,第一个参数为时间,第二个参数为函数名
timer.start() # 启用定时器
timer = threading.Timer(1, fun_timer) # 首次启动
timer.start()
# ===========================================================================
# datetime
# ===========================================================================
def func():
print("定时执行脚本")
# 如果需要循环调用,就要添加以下方法
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()
python3 定时控制
最新推荐文章于 2024-04-26 11:30:42 发布
该博客介绍了如何使用Python3的threading模块创建定时器进行任务调度。首先展示了一个5秒间隔调用fun_timer函数的例子,然后通过datetime模块设置定时执行脚本,并能根据当前时间计算延迟执行的时间,实现精确的定时任务执行。
343

被折叠的 条评论
为什么被折叠?



