首頁  >  文章  >  後端開發  >  透過Python3實現任務的定時循環執行

透過Python3實現任務的定時循環執行

anonymity
anonymity原創
2019-04-19 13:15:1612802瀏覽

在我們的實際開發中,常有這樣的需求:要求某個功能模組或任務在相同的時間週期內進行循環執行。這裡有了一個定時器的概念,具體而言我們該如何去實作一個定時器呢?定時器有許多很實用的功能,能夠控制執行緒的執行、減少系統的消耗等。現在我們就來動手實作實現Python3中的定時功能吧。

透過Python3實現任務的定時循環執行

例如使用Python在進行爬蟲系統開發時可能就需要間隔一段時間就重複執行的任務的需求,從而實現一個執行緒服務在後台監控數據的抓取狀態,這裡定時器就可以幫忙了。

【影片推薦:Python3影片教學

【手冊推薦:Python中文手冊

透過Python的文檔我們可以找到threading.Timer()來實作定時功能:

簡單實作程式碼:

import threading
def func1(a):
    #Do something
    print('Do something')
    a+=1
    print(a)
    print('当前线程数为{}'.format(threading.activeCount()))
    if a>5:
        return
    t=threading.Timer(5,func1,(a,))
    t.start()

效果圖:

透過Python3實現任務的定時循環執行

# #透過查閱資料,利用Python能實現三種不同的定時任務執行方式:

1.定時任務代碼

#!/user/bin/env python
#定时执行任务命令
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  os.system(cmd)
  print('task')
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

2.週期性執行任務

#!/user/bin/env python
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  #在inc秒后再次运行自己,即周期运行
  schedule.enter(inc, 0, perform_command, (cmd, inc))
  os.system(cmd)
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()#持续运行,直到计划时间队列变成空为止
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

3 .循環執行指令

#!/user/bin/env python
import time,os
def re_exe(cmd,inc = 60):
  while True:
    os.system(cmd)
    time.sleep(inc)
re_exe("echo %time%",5)

總結而言:Python實作定時器的方法都是schedule和threading的實現,具體的用法還要根據實際情況靈活運用。


最常用的兩個模組:threading、Sched

threading模組使用:


import threading ,time
from time import sleep, ctime
class Timer(threading.Thread):
        """
        very simple but useless timer.
        """
        def __init__(self, seconds):
                self.runTime = seconds
                threading.Thread.__init__(self)
        def run(self):
                time.sleep(self.runTime)
                print ("Buzzzz!! Time's up!")
class CountDownTimer(Timer):
        """
        a timer that can counts down the seconds.
        """
        def run(self):
                counter = self.runTime
                for sec in range(self.runTime):
                        print (counter)
                        time.sleep(1.0)
                        counter -= 1
                print ("Done")
 
class CountDownExec(CountDownTimer):
        """
        a timer that execute an action at the end of the timer run.
        """
        def __init__(self, seconds, action, args=[]):
                self.args = args
                self.action = action
                CountDownTimer.__init__(self, seconds)
        def run(self):
                CountDownTimer.run(self)
                self.action(self.args)
 
def myAction(args=[]):
        print ("Performing my action with args:")
        print (args)
 
if __name__ == "__main__":
        t = CountDownExec(3, myAction, ["hello", "world"])
        t.start()
        print("2333")

Sched模組使用:


'''
使用sched模块实现的timer,sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,
可以使用while循环的方式不停的调用该方法
'''
import time, sched
#被调度触发的函数
def event_func(msg):
    print("Current Time:", time.strftime("%y-%m-%d %H:%M:%S"), 'msg:', msg)
def run_function():
    #初始化sched模块的scheduler类
    s = sched.scheduler(time.time, time.sleep)
    #设置一个调度,因为time.sleep()的时间是一秒,所以timer的间隔时间就是sleep的时间,加上enter的第一个参数
    s.enter(0, 2, event_func, ("Timer event.",))
    s.run()
def timer1():
    while True:
        #sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,可以使用while循环的方式不停的调用该方法
        time.sleep(1)
        run_function()
if __name__ == "__main__":
    timer1()

以上是透過Python3實現任務的定時循環執行的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn