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

yipeiwu_com5年前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发送http请求解析返回json的实例

python发起http请求,并解析返回的json字符串的小demo,方便以后用到。 #! /usr/bin/env python # -*- coding:gbk -*-...

浅谈python中的变量默认是什么类型

1、type(变量名),输出的结果就是变量的类型; 例如 >>> type(6) <type 'int'> 2、在Python里面变量在声明时,不需要指定变...

python中PS 图像调整算法原理之亮度调整

亮度调整 非线性亮度调整: 对于R,G,B三个通道,每个通道增加相同的增量。 线性亮度调整: 利用HSL颜色空间,通过只对其L(亮度)部分调整,可达到图像亮度的线性调整。但是,RGB和H...

用python分割TXT文件成4K的TXT文件

复制代码 代码如下:########################## # # # 为了避免截断中文字符 # # 文件要求是 unicode 编码 # # txt文件另存为对话框下面有...

Python3.4实现从HTTP代理网站批量获取代理并筛选的方法示例

本文实例讲述了Python3.4实现从HTTP代理网站批量获取代理并筛选的方法。分享给大家供大家参考,具体如下: 最近在写爬虫,苦于不采用代理的情况下,默认的IP不出几分钟就被封了,故而...