簡體   English   中英

python:如何進行定期非阻塞查找

[英]python: how-to do a periodic non-blocking lookup

您能否建議如何定期執行比定期間隔花費更多時間的任務?

例如:

def lookup():
    # do some lookups, retrieve info, let's assume it takes 60sec to complete
    msg = {'abc':123}
    time.sleep(60)
    return msg

class Publisher(object):
    def __init__(self):
        self._TIMEIT = 0
        self._INTERVAL = 5
        self._counter = 0

    def xxx():
        t_start = time.time()
        msg = lookup()
        # do something with the value returned
        save_msg_to_db(msg)
        self._counter += 1
        t_end = time.time()
        self._TIMEIT = int(math.ceil(t_end - t_start))

    def run():
        while True:
            # let's do the lookup every 5sec, but remember that lookup takes 60sec to complete
            time.sleep(self._INTERVAL)
            # the call to xxx() should be non-blocking
            xxx()

但是run方法負責安排定期任務,並且在進行迭代時,調用函數xxx時不應阻塞它。

我正在考慮在每次對xxx函數的調用上創建一個事件循環,如不良協同程序示例中所述,但是如何對xxx非阻塞調用呢?

PS。 我正在使用asyncio新增的Python3.4(過去使用過gevent),不確定我是否在這里問某事。

因此, lookup將創建一個異步循環,比如說需要60秒才能完成。 但是,在run方法中有一個無限循環運行,我希望它每5秒執行一次查找,換句話說,我想(1)調用查找函數的頻率 (2)多長時間無關需要查找才能完成

由於您的lookup()主要是I / O密集型的,因此您可以將xxx()方法作為線程運行,並且可以很好地工作(為簡潔起見,代碼縮短了):

import threading
import time

class Publisher(object):

    def __init__(self):
        self._INTERVAL = 5
        self._counter = 0
        self._mutex = threading.Lock()

    def xxx(self):
        msg = lookup()
        save_msg_to_db(msg)
        with self._mutex:  # make sure only one thread is modifying counter at a given time
            self._counter += 1

    def run(self):
        while True:
            time.sleep(self._INTERVAL)
            t = threading.Thread(target=self.xxx)
            t.setDaemon(True)  # so we don't need to track/join threads
            t.start()  # start the thread, this is non-blocking

暫無
暫無

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

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