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

yipeiwu_com6年前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的schedule定时任务模块二次封装方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现Const详解

python语言本身没有提供const,但实际开发中经常会遇到需要使用const的情形,由于语言本身没有这种支出,因此需要使用一些技巧来实现这一功能 定义const类如下 复制代码 代码...

使用Selenium破解新浪微博的四宫格验证码

使用Selenium破解新浪微博的四宫格验证码

在我们爬虫的时候经常会遇到验证码,新浪微博的验证码是四宫格形式。 可以采用模板验证码的破解方式,也就是把所有验证码的情况全部列出来,然后拿验证码的图片和这所有情况中的图片进行对比,然后获...

Python开发的HTTP库requests详解

Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网...

解决python删除文件的权限错误问题

使用os.remove删除文件,总是遇到错误:PermissionError: WinError 找了很久没找到什么原因,以为是windows系统的问题,最后发现是删除了一个没有关闭的文...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...