如何每2分钟向变量添加1,直到达到100。
该程序将从0开始计算数字,并在每2分钟内将每1个数字相加,直到达到100。
2 min later
0/100 ------> 1/100
使用时间模块的睡眠功能
from time import sleep
i = 0
while i <= 100:
sleep(120)
i += 1
我用过睡眠!
from time import sleep
for i in range(100):
sleep(120)
# print(i)
如果需要制作进度条,也可以检查tqdm
。
from tqdm import tqdm
import time
for _ in tqdm(range(100)):
time.sleep(120)
一线解决方案:
from time import sleep
for t in range(100): time.sleep(120)
我相信到目前为止提供的所有解决方案都是线程锁定??
import asyncio, time
async def waitT(tWait, count):
print(count)
while count < 100: #The 100 could be passed as a param to make it more generic
await asyncio.sleep(tWait)
count = count + 1
print(count)
return
async def myOtherFoo():
#Do stuff in here
print("aaa")
await asyncio.sleep(2)
print("test that its working")
return
async def main(count):
asyncio.gather(myOtherFoo(), waitT(120, count)) #Obviously tweak 120 to whatever interval in seconds you want
return
if __name__ == "__main__":
count = 0
asyncio.create_task(main(count))
一个简单的,希望可读的异步解决方案。不检查正在运行的循环等,但应该为您打开一系列在计数器中的每次更新之间采取行动的可能性。