python的schedule定時任務模組二次封裝

風楚顏發表於2018-06-08

通過定時來執行任務,我們日常工作生活中會經常用到。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)


相關文章