-2

我试图让饥饿变量增加一非常三分钟,而我正在运行其他代码。使用 time.sleep() 只是停止整个代码。有没有办法做到这一点?

Hunger=1
If Hunger=1:
    sleep(180)
    Hunger-=1
4

2 回答 2

2

这是线程的工作:

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
于 2013-05-23T23:54:58.763 回答
1

如果你需要很多这些类型的东西来异步运行并且它是一个大型项目,你可以考虑使用像 celery 这样的异步任务队列库(http://docs.celeryproject.org/en/latest/getting-started/introduction .html)。当然,这可能开销太大 - 不知道您的项目正在尝试做什么。

您将定义一个名为 的任务increase_hunger,例如:

@celery.task
def increase_hunger():
hunger=1
while True:
    sleep(180)
    hunger+=1

在您的主代码中,调用add_hunger.apply_async()将从另一个地方启动此任务。有关将任务代码放置在何处以及如何设置 celery 项目的详细信息,您应该阅读本教程。

另一种方法是使用像 celery beat ( http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html ) 之类的东西作为定期后台任务来执行此操作,但这听起来不像您的用例。

于 2013-05-24T00:10:07.863 回答