gpt4 book ai didi

python - 在 celery 任务中设置 while 循环

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:52 25 4
gpt4 key购买 nike

我希望在我的网络服务器后台有一个持续运行的 while 循环。我仍然希望能够使用 flask 向我的 celery worker 发出命令来打开和关闭循环。 celery 中的 while 循环似乎只运行一次。

from celery import Celery    
@app.task
def count(i):
if i == 1: # turn on command
while True: # a while loop to achieve what I want to do
i = i+1
return i
elif i == 0: # turn off command given by flask
return i

我也尝试过 celery_beat,但这需要我提前给出参数,而不是接受来自其他来源的命令。

app.conf.update(
CELERYBEAT_SCHEDULE = {
'add-every-1-seconds': {
'task': 'tasks.count',
'schedule': timedelta(seconds=1),
#'args': (1)
},
})

最佳答案

感谢@dim 的回答。我现在的代码是:

@app.task
def count(i):
if i == 1:
while True: # a while loop to achieve what I want to do
i = i+1
time.sleep(1)
print i
print 'i am counting'

启动工作线程:

$ celery -A tasks worker -l info

并从 python 中调用它

>> from tasks import count
>> result = count(1)

停止 python 循环

>> result.revoke(terminate=True)

希望这对那些想要在 celery 任务中循环的人有用。

关于python - 在 celery 任务中设置 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com