0

我大约每 2.5 秒从外部源(在这种情况下为串行端口)输入数据。
我想每 5 分钟而不是每 2.5 秒存储(在 mysql 中)这个数据的样本。
我将如何在 python 中实现它?
可能不能使用睡眠功能,因为这将停止脚本的其余部分。

4

2 回答 2

1

检查自上次保存每个传入事件以来已经过去了多少时间,并在每次保存后更新上次保存时间戳:

import time
lastsave = 0
def SaveEvent(data):
    # do what you need to save it
    ...


# I'm assuming there's some sort of event loop that 
# detects new events and directs them to some HandleEvent function

def HandleEvent(data):
    global lastsave
    if time.time() - lastsave > 300: 
    # this is in seconds, so 5 minutes = 300 seconds
        lastsave = time.time()
        SaveEvent(data)

如果您的应用程序是多线程或多处理的,您还应该考虑在SaveEvent函数中实现锁定以避免并发保存。

于 2013-02-01T21:41:30.380 回答
1

只需使用Timer来自threading- 之类的类。

import time
from threading import Timer

def poll_port():
    print "Getting my data from port", time.time()

def main():
    print "Main:enter", time.time()
    while True:
        t = Timer(5, poll_port)
        t.start()
        t.join()
        print "after join:", time.time()

if __name__ == "__main__":
    main()

示例输出:

Main:enter 1359755186.87
Getting my data from port 1359755191.88
after join: 1359755191.88
Getting my data from port 1359755196.88
after join: 1359755196.88
Getting my data from port 1359755201.88
after join: 1359755201.88
Getting my data from port 1359755206.88
于 2013-02-01T21:47:14.093 回答