Python 让事情随着时间的推移而发生
我试图让一个饥饿变量每三分钟增加一个,同时运行其他代码。使用time.sleep()只会停止整个代码。有办法做到这一点吗Python 让事情随着时间的推移而发生,python,time,Python,Time,我试图让一个饥饿变量每三分钟增加一个,同时运行其他代码。使用time.sleep()只会停止整个代码。有办法做到这一点吗 Hunger=1 If Hunger=1: sleep(180) Hunger-=1 这是一个线程作业: import thread, time hunger = 0 def decreaseHunger(): global hunger while True: time.sleep(180) hunger
Hunger=1
If Hunger=1:
sleep(180)
Hunger-=1
这是一个线程作业:
import thread, time
hunger = 0
def decreaseHunger():
global hunger
while True:
time.sleep(180)
hunger -= 1
thread.start_new_thread(decreaseHunger, ())
# you can do other stuff here, and it will continue to decrease hunger
# every 2 minutes, while the other stuff happens as well
如果你需要很多类型的东西异步运行,这是一个大项目,你可以考虑使用像芹菜()这样的异步任务队列库。当然,这可能是太多的开销-不知道您的项目正在尝试做什么
您可以定义一个名为“增加饥饿感”的任务,例如:@celery.task
def increase_hunger():
hunger=1
while True:
sleep(180)
hunger+=1
在主代码中,调用add\u hunger.apply\u async()
将从其他位置启动此任务。有关将任务代码放置在何处以及如何设置芹菜项目的详细信息,请阅读本教程
另一种方法是使用类似芹菜节拍()的东西作为定期的背景任务,但这听起来不像您的用例。这是错误的语法:
If
->If
;在语句=
->=
中。并在运算符前后使用空格(PEP 8约定)此代码的上下文是什么?这是一个60 fps循环的游戏,比如pygame,还是一个控制台程序?如果你想让饥饿变量增加,为什么要从中减去一个?我认为在分配给全局变量时需要global
。因为hunger
很可能是一个全局变量,也会被主线程访问,此线程,它需要使用thread.LockType
或threading.Lock
对象来序列化对其值的并发访问。