首頁 後端開發 Python教學 透過Python3實現任務的定時循環執行

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

Apr 19, 2019 pm 01:15 PM
python3 threading time

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

time包的單調時鐘處理 time包的單調時鐘處理 Aug 04, 2023 pm 05:45 PM

我們今天主要是來看看golang time 套件的時間應用方式。兩者的一般規則是“wall time”用於告知時間,而“monotonic clock”用於測量時間;除外還有其他的時鐘處理方式。

Java8 Time Api如何使用 Java8 Time Api如何使用 Apr 28, 2023 pm 12:25 PM

1.概述作為本文的一部分,讓我們從現有Date和CalendarAPI存在的一些問題入手,來探討新的Java8Date和TimeAPI如何解決這些問題。我們也將搞一搞Java8時間類別庫中的核心類,例如LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Period,Duration以及它們的api。 2.舊的時間API(java8之前)的問題線程安全-Date和Calendar類別不是線程安全的,使開發者難以調試這些api的並發問題,需要編寫額外的程式碼來處

python中time和datetime的差別及用法是什麼 python中time和datetime的差別及用法是什麼 May 02, 2023 am 11:01 AM

一.Python中表示時間的兩種方式:時間戳:相對於1970.1.100:00:00以秒計算的偏移量,唯一的時間元組struct_time:共有9個元素>tm_year:年1-12> tm_mon:月1-12>tm_mday:日1-31>tm_hour:時0-23>tm_min:分0-59>tm_sec:秒0-59>tm_wday:星期0-6(0表示週日)>tm_day:一年中的第幾天1-366>tm_isdst:是否為夏令,預設為-1二.ti

Python time模組時間怎麼取得與轉換 Python time模組時間怎麼取得與轉換 May 13, 2023 pm 12:19 PM

Pythontime模組時間取得和轉換Python的Time庫可以進行時間相關的處理,例如存取當前日期和時間,輸出不同格式的時間以及等待指定的時間等。 1.取得時間1.1.時間戳importtimetimestamp=time.time()#1682737552.5009851格林威治時間(GMT)1970年01月01日00時00分00秒起至現在的總秒數1.2.結構化時間01日00時00分00秒起至現在的總秒數1.2.結構化時間importstructtime_time= time.localtime()#time.struct_time(tm_year=2

Python 3.x 中如何使用threading模組建立和管理線程 Python 3.x 中如何使用threading模組建立和管理線程 Aug 04, 2023 am 10:37 AM

Python3.x中如何使用threading模組建立和管理執行緒簡介:隨著電腦的強大效能,多執行緒成為一種常見的平行處理方式。而在Python的標準函式庫中,就有一個方便的模組-threading。本文將介紹如何使用Python3.x中的threading模組建立和管理線程,並使用程式碼範例進行說明。一、什麼是線?執行緒是一個在單一進程中執行的獨立流程。

python3如何安裝pip python3如何安裝pip Dec 20, 2023 pm 05:42 PM

安裝步驟:1、確保已經安裝了Python3,並且可以透過命令列存取;2、開啟終端,輸入「python3 -m ensurepip --upgrade」命令來安裝pip;3、從Python官方網站下載pip的安裝包; 4.將下載的pip安裝包解壓縮到一個目錄中;5、開啟終端,並導航到解壓縮後的pip目錄;6、執行「python3 setup.py install」指令安裝pip即可。

使用PHP函數 'time' 傳回目前的UNIX時間戳 使用PHP函數 'time' 傳回目前的UNIX時間戳 Jul 25, 2023 pm 04:42 PM

使用PHP函數"time"傳回目前的UNIX時間戳UNIX時間戳是指從協調世界時(UTC)1970年1月1日0時0分0秒起至今的總秒數。在PHP中,可以使用內建函數"time"來取得目前的UNIX時間戳記。本文將介紹如何使用這個函數,並提供對應的程式碼範例。程式碼範例:<?php$timestamp=time();echo"目前的

如何解決 golang 中的 'undefined: time.After” 錯誤? 如何解決 golang 中的 'undefined: time.After” 錯誤? Jun 25, 2023 pm 05:28 PM

Golang是一門非常受歡迎的程式語言,其簡單易學、高效快速的特性吸引了越來越多的開發者。但在使用中,不可避免地會遇到一些問題和錯誤。例如,使用time套件中的After方法時,可能會遇到undefined:time.After的錯誤。本篇文章將為大家介紹如何解決這個錯誤。了解錯誤原因在Golang中,如果我們使用了一個未導出的函數名稱或未正

See all articles