python 定时器,实现每天凌晨3点执行的方法

yipeiwu_com5年前Python基础

如下所示:

'''
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设计】。

相关文章

Python3 log10()函数简单用法

描述 log10() 方法返回以10为基数的x对数,x>0。 语法 以下是 log10() 方法的语法: import math math.log10( x ) 注意...

最基础的Python的socket编程入门教程

本文介绍使用Python进行Socket网络编程,假设读者已经具备了基本的网络编程知识和Python的基本语法知识,本文中的代码如果没有说明则都是运行在Python 3.4下。 Pyth...

Python使用dis模块把Python反编译为字节码的用法详解

dis — Disassembler for Python bytecode,即把python代码反汇编为字节码指令. 使用超级简单: python -m dis xxx.py...

Python编程中的for循环语句学习教程

Python编程中的for循环语句学习教程

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 语法: for循环的语法格式如下: for iterating_var in sequence: s...

浅谈解除装饰器作用(python3新增)

一个装饰器已经作用在一个函数上,你想撤销它,直接访问原始的未包装的那个函数。 假设装饰器是通过 @wraps 来实现的,那么你可以通过访问 wrapped 属性来访问原始函数: &g...