我尝试做的是打印或执行某个特定的字符串,如果这个函数是20秒,问题在第二个循环上,当然它在第一个循环上等待了20秒,但第二个循环不再等待,它只是继续打印。为什么会发生这种情况?我怎么才能解决这个问题呢?
from threading import Timer
import time
startlog = time.time()
def tess():
tm = 0
while True:
tm += 1
print(tm)
tess()
time.sleep(1)
发布于 2019-01-05 22:27:04
你需要在“成功”的tess调用之间重置startlog (已经过了20秒),这段代码按照你想要的方式工作(但是因为全局变量太难看了)。
import time
startlog = time.time()
def tess():
global startlog
if time.time() - 20 > startlog:
print('its been 20 secs')
startlog = time.time()
tm = 0
while True:
tm += 1
print(tm)
tess()
time.sleep(1)
发布于 2019-01-05 22:28:23
您必须将start = time.time()
更改为startlog = time.time()
,并将变量定义为global
或nonlocal
def tess():
nonlocal startlog
...
startlog = time.time()
或者只是等待20秒:time.sleep(20)
发布于 2019-01-05 22:28:53
您需要在tess()函数中更新循环内的startlog变量。你需要更换
start = time.time()
使用:
startlog = time.time()
https://stackoverflow.com/questions/54052906
复制相似问题