【发布时间】:2013-08-27 20:17:39
【问题描述】:
我在 python 2.74 上使用 threading.Timer。这是相关的代码:
__lock = threading.Lock()
def RegeneratePopulationData():
__lock.acquire()
print 'I feel regenerated!'
__lock.release()
def __setRegenerationTimer(firstTime = False):
global __regenerationTimer
now = _getNow().date()
nextRun = datetime(now.year, now.month, now.day + 1, 2, 0)
__regenerationTimer = threading.Timer((nextRun - _getNow()).total_seconds(), __setRegenerationTimer)
print 'Regeneration timer set to run in %s' % (nextRun - _getNow())
print __regenerationTimer.interval
__regenerationTimer.start()
if not firstTime:
RegeneratePopulationData()
def _getNow():
return datetime.now() + timedelta(hours = TIME_DIF)
这会导致从 threading.py 抛出 TypeError 异常。我已经在网上搜索了几个小时,但找不到解决方案。
将 threading.py 中的代码(出于调试目的)在第 349 行附近更改为:
# than 20 times per second (or the timeout time remaining).
print _time()
print timeout
endtime = _time() + timeout
delay = 0.0005 # 500 us -> initial delay of 1 ms
这是我得到的例外:
Regeneration timer set to run in 2:52:12.337000
10332.337
1377634067.66
10332.337
1377634067.66
2013-08-27 21:07:47.663000
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 812, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 1082, in run
self.finished.wait(self.interval)
File "C:\Python27\lib\threading.py", line 622, in wait
self.__cond.wait(timeout)
File "C:\Python27\lib\threading.py", line 350, in wait
endtime = _time() + timeout
TypeError: unsupported operand type(s) for +: 'float' and 'datetime.datetime'
我不明白为什么间隔突然变成了日期时间!
有人可以帮忙吗?
【问题讨论】:
-
双下划线是怎么回事?你通常只在类定义中看到那些,但这段代码中没有
self。 -
我打算建议您将
id(self)添加到threading.py 中的跟踪中,以查看您的程序中是否有另一个对象在等待。但是您接受了@Marin 的回答……这是否意味着问题已解决? -
@tdelaney 这就是我最终所做的,这就是问题所在。由于我错误地将问题提出为源于 threading.py,因此我接受了这个答案,因此没有人会在这个问题上浪费时间......他的最后建议是调试,这就是我最终选择它的方式。
标签: python multithreading python-2.7