我有一个需要在一定时间间隔内执行的程序。比如说,我可能希望它每五分钟执行一次。我有几个协调器与多个终端节点设备进行通信。下面的代码位于协调器上。如果间隔设置为5,则需要在例如9:05、9:10、9:15、9:20、9:25等时刻运行并记录信息。到目前为止,我的代码如下:
if __name__ == '__main__':
while True:
try:
r = json.read(rqst_command())
interval = r.get('intvl')
collect_time = r.get('c_time')
command = r.get('cmd')
send_stats(cmd_nodes(command, collect_time))
time.sleep(interval)
except Exception, e:
print e
print "**Top Level Exception"
pass
问题在于,如果我将间隔设置为5分钟,它并不会精确地每5分钟记录一次。执行时间似乎会慢慢增加这个时间。例如,上面的代码可能记录为9:05:09, 9:10:19, 9:15:29, 9:20:41, 9:25:50。程序运行所需的时间取决于节点通信的速度。
有人有什么想法吗?我该如何更改代码,以便程序能够精确地每5分钟执行一次?
编辑/更新
我想我已经找到了解决我的问题的方法。我获取当前的
datetime
,然后检查它是否在5分钟标记上。如果是,则记录datetime
并将其发送到send_stats
函数。这样datetime
将始终是我想要的。如果不是在5分钟标记上,则sleep
一段时间,然后再次检查。我已经基本完成了代码。但是,当我运行程序时,我收到以下错误:'builtin_function_or_method' object has no attribute 'year'
。我做错了什么?
下面是我的新代码:
import os
import json
import datetime
from datetime import datetime
import urllib2
from urllib import urlencode
from socket import *
import time
import zigbee
import select
if __name__ == '__main__':
while True:
try:
r = json.read(rqst_command())
interval = r.get('intvl')
collect_time = r.get('c_time')
command = r.get('cmd')
tempTest = True
while tempTest == True:
start_time = datetime.now
compare_time = datetime(start_time.year, start_time.month, start_time.day, start_time.hour, 0, 0)
difff = int((start_time - compare_time).total_seconds() / 60)
if((difff % interval) == 0):
c_t = datetime(start_time.year, start_time.month, start_time.day, start_time.hour, start_time.minute, 0)
send_stats(cmd_nodes(command, collect_time), c_t)
tempTest = False
else:
time.sleep(30)
except Exception, e:
print e
print "**Top Level Exception"
pass
start_time = datetime.now
是错误的。now
是方法的名称,你必须调用它:start_time = datetime.now()
。顺便说一句,在将代码放到特殊设备上之前,也许你应该在一个易于调试的平台上运行它。 - Dr. Jan-Philip Gehrcke