Tornado gen协同程序中的Tornado异步作业

2024-04-25 23:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个应用程序,它从队列中获取作业并异步执行它。在

def job(self):
    print 'In job'
    time.sleep(0.01)

@gen.coroutine
def start_jobs(self):
    jobs = filter(lambda x: x['status'] == 0, self.queue)
    for job in jobs:
        yield self.job()
    print 'exit from start job'

但是,这个代码不起作用。在

输出:

在职

在职

在职等

如何正确地执行?在

我如何让它与未来一起工作,还有没有一种更简单的方法来对付龙卷风?在


Tags: inself应用程序time队列def作业jobs
1条回答
网友
1楼 · 发布于 2024-04-25 23:35:27

千万不要在龙卷风中呼叫time.sleep!请改用yield gen.sleep。在

使用pip install toro安装Toro并使用JoinableQueue:

import random
from tornado import ioloop, gen
import toro


class C(object):
    def __init__(self):
        self.queue = toro.JoinableQueue()

    @gen.coroutine
    def start_jobs(self):
        while True:
            job_id = yield self.queue.get()
            self.job(job_id)

    @gen.coroutine
    def job(self, job_id):
        print 'job_id', job_id
        yield gen.sleep(random.random())
        print 'job_id', job_id, 'done'
        self.queue.task_done()


c = C()
for i in range(5):
    c.queue.put_nowait(i)

c.start_jobs()

io_loop = ioloop.IOLoop.instance()

# block until all tasks are done
c.queue.join().add_done_callback(lambda future: io_loop.stop())
io_loop.start()

从Tornado 4.2开始,Torro是Tornado的一部分,因此您可以只执行queue = tornado.queues.Queue()而不是使用Toro JoinableQueue:

http://tornado.readthedocs.org/en/latest/releases/v4.2.0.html#new-modules-tornado-locks-and-tornado-queues

相关问题 更多 >