python 定时器 timer QTimer

需求背景:

一秒记录一个数据,数据从仪器读取,经过一系列的操作后记录到csv文件(该过程从发命令到成功写入CSV需要的操作时间不等,从几毫秒到几百毫秒),记录时间一天左右!

==========================================================================

第一次实现 使用 time.sleep()

 1 import time  
 2 import datetime
 3 
 4 def hello():
 5     now = datetime.datetime.now()
 6     print(str(now))
 7     fh = open("test.csv",'a')
 8     fh.write(str(now))
 9     fh.write('
')
10     fh.flush()
11     time.sleep(0.1) #模拟实际代码执行时间
13 if __name__ == "__main__": 
14   while True:
15     hello()
16     time.sleep(1)

结果:

 从上图中看出,这不合要求,少了15:37:04 时刻的数据,因为每次循环,代码执行的时间都在累加,导致实际记录间隔是 1s+代码执行时间。

第二次实现  python Timer 定时器

补充Timer知识点

class threading.Timer(intervalfunctionargs=[]kwargs={})

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.

For example:

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed

通过测试这里最大的问题是,hello()只执行一次,但实际要的效果是每隔1s连续不断的执行hello(),于是通过百度找到下面方法:

import threading
import time  
import datetime

def hello(uut_dev,cmd):
    now = datetime.datetime.now()
    print(str(now))
    fh = open("test.csv",'a')
    fh.write(str(now))
    fh.write('
')
    fh.flush()
    time.sleep(0.2) #模拟实际代码执行时间
    t1 = threading.Timer(1, hello,("uut_dev","FETCH?
"))
    t1.start()

if __name__ == "__main__":
    t1 = threading.Timer(1, hello,("uut_dev","FETCH?
"))
    t1.start()

代码执行结果:

 很明显又是一次不合格的数据,于是又想了下面的方法:

 1 import threading
 2 import time  
 3 import datetime
 4 
 5 def hello(uut_dev,cmd):
 6     now = datetime.datetime.now()
 7     print(str(now))
 8     fh = open("test.csv",'a')
 9     fh.write(str(now))
10     fh.write('
')
11     fh.flush()
12     time.sleep(0.2)
13 
14 if __name__ == "__main__":
15     while True:
16         t1 = threading.Timer(0, hello,("uut_dev","FETCH?
"))
17         t1.start()
18         time.sleep(1)

执行结果:

 从结果看出,效果好了很多,但每次执行还是多了大概3ms,很明显要是执行的时间足够长肯定还是会有记录误差

第三次实现  pyqt QTimer 定时器

 1 import sys
 2 import datetime
 3 import time
 4 from PyQt4.QtGui import *
 5 from PyQt4.QtCore import *
 6 
 7 def hello():
 8     now = datetime.datetime.now()
 9     print(str(now))
10     fh = open("test.csv",'a')
11     fh.write(str(now))
12     fh.write('
')
13     fh.flush()
14     time.sleep(0.2)
15 
16 if __name__ == "__main__":
17     app = QApplication(sys.argv)
18     timer = QTimer()
19     QObject.connect(timer,SIGNAL("timeout()"), hello)
20     timer.start(1000)
21     sys.exit(app.exec_())

执行结果:

 好像就是需要的效果,虽然每次执行有几毫秒的误差,但能保证长时间的1s一次记录

原文地址:https://www.cnblogs.com/njuptlwh/p/13932285.html