python的schedule定时任务模块二次封装方法
通过定时来执行任务,我们日常工作生活中会经常用到。python有schedule这个库,简单好用,比如,可以每秒,每分,每小时,每天,每天的某个时间点,间隔天数的某个时间点定时执行,另外自己又写了一个可以自定义时间点来定时执行任务,代码如下。
importschedule
importtime
classTiming():
#按秒循环定时执行任务
defdoEverySecond(self,seconds,job_func):
try:
schedule.every(seconds).seconds.do(job_func)
whileTrue:
schedule.run_pending()
exceptExceptionase:
raisee
#按分钟循环定时执行任务
defdoEveryMinutes(self,minutes,job_func):
try:
schedule.every(minutes).minutes.do(job_func)
whileTrue:
schedule.run_pending()
exceptExceptionase:
raisee
#按小时循环定时执行任务
defdoEveryHours(self,Hours,job_func):
try:
schedule.every(Hours).minutes.do(job_func)
whileTrue:
schedule.run_pending()
exceptExceptionase:
raisee
#按天数在某个时刻定时执行任务
defdoEveryDay(self,time,job_func,days=1):
try:
schedule.every(days).days.at(time).do(job_func)
whileTrue:
schedule.run_pending()
exceptExceptionase:
raisee
#设置在每天的多个时刻定时执行任务,这个方法在实际工作中比较常用到
defdoEveryTime(self,time_str,job_func,days=1):
'''
:paramtime_str:
:paramjob_func:
:paramdays:
:return:None
example:time_str="10:30","10:45","11:00"
'''
try:
list_time=time_str.split(",")
fortimeinlist_time:
schedule.every(days).days.at(time).do(job_func)
whileTrue:
schedule.run_pending()
exceptExceptionase:
raisee
#自定义时间,dateTimes格式为:"2018-06-0816:55,2018-06-0816:56"
defdoJustTime(self,datestr,job_func):
try:
date_list=datestr.split(",")
foriindate_list:
#转换为unix时间戳格式
timeArray=time.strptime(i,"%Y-%m-%d%H:%M")
timestamp=time.mktime(timeArray)
whileTrue:
now_time=round(time.time(),0)
iftimestamp==now_time:
job_func()
break
else:
time.sleep(1)
exceptExceptionase:
raisee
if__name__=="__main__":
defprint1():
print("ok")
Timing().doJustTime('2018-06-0817:53,2018-06-0817:54',print1)
以上这篇python的schedule定时任务模块二次封装方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。