欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python的schedule定时任务模块二次封装方法

时间:2021-04-29 10:57:39|栏目:Python代码|点击:

通过定时来执行任务,我们日常工作生活中会经常用到。python有schedule这个库,简单好用,比如,可以每秒,每分,每小时,每天,每天的某个时间点,间隔天数的某个时间点定时执行,另外自己又写了一个可以自定义时间点来定时执行任务,代码如下。

import schedule
import time
 
class Timing():
 
 #按秒循环定时执行任务
 def doEverySecond(self,seconds,job_func):
  try:
   schedule.every(seconds).seconds.do(job_func)
   while True:
    schedule.run_pending()
 
  except Exception as e:
   raise e
 
 # 按分钟循环定时执行任务
 def doEveryMinutes(self,minutes,job_func):
  try:
   schedule.every(minutes).minutes.do(job_func)
   while True:
    schedule.run_pending()
 
  except Exception as e:
   raise e
 
 # 按小时循环定时执行任务
 def doEveryHours(self,Hours,job_func):
  try:
   schedule.every(Hours).minutes.do(job_func)
   while True:
    schedule.run_pending()
 
  except Exception as e:
   raise e
 
 
 #按天数在某个时刻定时执行任务
 def doEveryDay(self,time,job_func,days=1):
  try:
   schedule.every(days).days.at(time).do(job_func)
   while True:
    schedule.run_pending()
  except Exception as e:
   raise e
 
 
 #设置在每天的多个时刻定时执行任务,这个方法在实际工作中比较常用到
 def doEveryTime(self,time_str,job_func,days=1):
  '''
  :param time_str:
  :param job_func:
  :param days:
  :return: None
  example:time_str="10:30","10:45","11:00"
  '''
 
  try:
   list_time = time_str.split(",")
   for time in list_time:
    schedule.every(days).days.at(time).do(job_func)
   while True:
    schedule.run_pending()
  except Exception as e:
   raise e
 
 #自定义时间,dateTimes格式为:"2018-06-08 16:55,2018-06-08 16:56"
 def doJustTime(self,datestr,job_func):
  try:
   date_list = datestr.split(",")
   for i in date_list:
    #转换为unix时间戳格式
    timeArray = time.strptime(i, "%Y-%m-%d %H:%M")
    timestamp = time.mktime(timeArray)
    while True:
     now_time = round(time.time(),0)
     if timestamp == now_time:
      job_func()
      break
     else:
      time.sleep(1)
 
  except Exception as e:
   raise e
 
 
if __name__ == "__main__":
 def print1():
  print("ok")
 Timing().doJustTime('2018-06-08 17:53,2018-06-08 17:54',print1)

上一篇:Python 解决中文写入Excel时抛异常的问题

栏    目:Python代码

下一篇:Python利用pandas处理Excel数据的应用详解

本文标题:python的schedule定时任务模块二次封装方法

本文地址:http://www.codeinn.net/misctech/111271.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有