在python线程中定时执行两个单独的任务

时间:2015-03-05 08:47:06

标签: python multithreading time milliseconds

我有一个Python线程,它使用pyserial打开与串口的连接。在这个线程中,我想每30毫秒只写一次串口,但是要尽可能快地从端口读取。

我的想法是在线程的run方法中检查30秒是否已经过了time.time(),如果没有,则跳过写入并继续读取。

当我运行下面的精简示例时,if块中的代码每2 ms左右运行一次(我希望每隔30 ms),这让我相信time.time()可能不够可靠到以这种方式使用,可能无法在线程内正常工作,或者我犯了一个愚蠢的错误。我在OSX上,Python 2.7

import threading
import time

class TestThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

        self.daemon = True

        self.last_time = 0
        self.next_update = 0
        self.current_time_ms = 0
        self.update_rate = 30

        self.alive = threading.Event()
        self.alive.set()

    def run(self):
        while self.alive.isSet():
            self.current_time_ms = int(round(time.time() * 1000))
            if self.current_time_ms >= self.next_update:

                # WRITE TO SERIAL PORT EVERY 30 MS

                print self.current_time_ms - self.last_time
                self.last_time = self.current_time_ms

        # READ FROM SERIAL PORT AS FAST AS POSSIBLE

if __name__ == "__main__":
    print "main"

    aThread = TestThread()
    aThread.start()

    while True:
        # Do nothing overe here
        pass

0 个答案:

没有答案