温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中设置定时器每天执行一次

发布时间:2021-04-19 18:03:56 来源:亿速云 阅读:5238 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关怎么在python中设置定时器每天执行一次,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

python可以做什么

Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,该语言通俗易懂、容易入门、功能强大,在许多领域中都有广泛的应用,例如最热门的大数据分析,人工智能,Web开发等。

1.实现功能

编写python脚本一直运行,判断当下是否是新的一天,如果是就执行一次任务代码

2.具体实现代码

#-*-coding:utf-8 -*-
__author__ = 'Administrator'
import os,threading,time
curTime=time.strftime("%Y-%M-%D",time.localtime())#记录当前时间
execF=False
ncount=0
def execTask():
  #具体任务执行内容
  print("execTask executed!")
def timerTask():
  global execF
  global curTime
  global ncount
  if execF is False:
    execTask()#判断任务是否执行过,没有执行就执行
    execF=True
  else:#任务执行过,判断时间是否新的一天。如果是就执行任务
    desTime=time.strftime("%Y-%M-%D",time.localtime())
    if desTime > curTime:
      execF = False#任务执行执行置值为
      curTime=desTime
  ncount = ncount+1
  timer = threading.Timer(5,timerTask)
  timer.start()
  print("定时器执行%d次"%(ncount))
if __name__=="__main__":
  timer = threading.Timer(5,timerTask)
  timer.start()

使用Python 执行具体任务执行

知识点扩展:

Python: 定时器(Timer)简单实现

项目分析中发现有网站下载过程中需要发送心跳指令,复习下定时器,其与javascript中实现方法类似。

其原理为执行函数中置定时函数Timer(),递归调用自己,看来实现方法比较拙劣。

假定1秒触发一次,并置结束条件为15秒:

import threading
import time
exec_count = 0
def heart_beat():
  print time.strftime('%Y-%m-%d %H:%M:%S')
  global exec_count
  exec_count += 1
  # 15秒后停止定时器
  if exec_count < 15:
    threading.Timer(1, heart_beat).start()
heart_beat()

另一种判断方式:

import threading
import time
cancel_tmr = False
def heart_beat():
  print time.strftime('%Y-%m-%d %H:%M:%S')
  if not cancel_tmr:
    threading.Timer(1, heart_beat).start()
heart_beat()
# 15秒后停止定时器
time.sleep(15) 
cancel_tmr = True

看完上述内容,你们对怎么在python中设置定时器每天执行一次有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI