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

相关文章

在pycharm中使用git版本管理以及同步github的方法

在pycharm中使用git版本管理以及同步github的方法

注意:首先你电脑必须安装git版本控制器(软件),在官网下载即可。 pycharm中使用git以及github很简单,首先在设置中搜索github: 点击右边的Create API T...

git使用.gitignore设置不生效或不起作用问题的解决方法

偶然遇到的问题,记录如下: 通常我们在push项目时,会有些配置文件或本地文件不想上传到服务器上 这时候我们会通过设置.gitignore  文件 一般设置成这样: ###...

带你认识Django

Django简介: Django,发音为[`dʒæŋɡəʊ],是用python语言写的开源web开发框架,并遵循MVC设计。劳伦斯出版...

python代码 FTP备份交换机配置脚本实例解析

python代码 FTP备份交换机配置脚本实例解析

代码如下 #!/bin/python #coding=utf-8 #python-version=2.75 #使用python2 from ftplib impo...

Python with关键字,上下文管理器,@contextmanager文件操作示例

本文实例讲述了Python with关键字,上下文管理器,@contextmanager文件操作。分享给大家供大家参考,具体如下: demo.py(with 打开文件): # ope...