Python schedule 模块二次封装:实现自定义时间点的定时任务

唐可
唐可
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍如何基于Python的schedule库进行二次封装,实现更灵活的定时任务执行。除了支持秒、分、时、天等常规周期外,重点演示了如何自定义精确到具体日期的时间点执行任务,并提供完整代码示例供参考。

在日常开发与运维中,周期性执行任务是非常常见的需求。Python生态中的schedule库以其简洁易用的特点广受欢迎,它支持按秒、分、小时、天以及特定时间点进行定时调度。此外,为了满足更精细的控制需求,这里介绍一种基于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 相关产品和应用

全部下载

专题列表