簡體   English   中英

python每分鍾線程化多個功能

[英]python threading multiple functions every minute

我有幾個函數想同時在無限循環中運行,但是所有函數應以不同的間隔運行。 例如,以下代碼:

while True:
   functionA()
   after 1 minute repeat
   functionB()
   after 2 minutes repeat

我知道使用time.sleep或dateime.now()很熱,但是我不知道如何在同一文件中讓functionA和B彼此獨立地運行和等待。

from threading import Timer

class Interval(object):
    """Interface wrapper for re-occuring functions."""

    def __init__(self, f, timeout):
        super(Interval, self).__init__()
        self.timeout = timeout
        self.fn = f
        self.next = None
        self.done = False
        self.setNext()


    def setNext(self):
        """Queues up the next call to the intervaled function."""
        if not self.done:
            self.next = Timer(self.timeout, self.run)
            self.next.start()

        return self


    def run(self):
        """Starts the interval."""
        self.fn()
        self.setNext()
        return self


    def stop(self):
        """Stops the interval. Cancels any pending call."""
        self.done = True
        self.next.cancel()
        return self

將函數和超時作為參數傳遞。 線程模塊中的Timer類完成了您所需的大部分操作(經過一定時間后運行一個函數),我添加的包裝器類僅添加了重復項,使其易於啟動,停止,傳遞等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM