使用带有asycnio的threading.Timer

时间:2016-12-30 16:11:36

标签: python multithreading asynchronous timer python-asyncio

我是python的ascynio功能的新手,我有一个处理来自浏览器的websocket请求的服务器。以下是其工作原理的简化版本:

@asyncio.coroutine
def web_client_connected(self, websocket):
    self.web_client_socket = websocket

    while True:
        request = yield from self.web_client_socket.recv()
        json_val = process_request(request)
        yield from self.socket_queue.put(json_val)

@asyncio.coroutine
def push_from_web_client_json_queue(self):
    while True:
        json_val = yield from self.socket_queue.get()
        yield from self.web_client_socket.send(json_val)

您有一个循环正在查找来自客户端的Web套接字请求。当它获得一个时,它处理它并将值放入队列。另一个循环是在该队列上查找值,当它找到一个时,它会在Web套接字上发回处理后的值。非常直接且有效。

我现在要做的是它引入一个计时器。当请求到来并且处理完毕,而不是立即将响应放回队列时,我想启动计时器1分钟。当计时器结束时,我想把响应放在队列上。

我尝试过类似的事情:

@asyncio.coroutine
def web_client_connected(self, websocket):
    self.web_client_socket = websocket

    while True:
        request = yield from self.web_client_socket.recv()
        json_val = process_request(request)
        t = threading.Timer(60, self.timer_done, json_val)
        t.start()

@asyncio.coroutine
def timer_done(self, args):
    yield from self.socket_queue.put(args)

虽然它没有用。永远不会调用timer_done方法。如果我删除了@asyncio.coroutine装饰器和yield from,则timer_done会被调用,但随后致电self.socket_queue.put(args)无法正常工作。

我想我在这里误解了一些根本性的东西。你是怎么做到的?

1 个答案:

答案 0 :(得分:1)

使用np.random.seed([3,1415]) data = pd.DataFrame(dict( Highschool=np.random.choice(('x', 'y', 'z'), 20), CreditScore=np.random.choice(('y', 'n'), 20), Scholarship=np.zeros(20) )) data.loc[ (data['Highschool']=='x') & (data['CreditScore']=='y'), 'Scholarship'] = 8.5 print(data) CreditScore Highschool Scholarship 0 y x 8.5 1 n z 0.0 2 n z 0.0 3 n z 0.0 4 n z 0.0 5 y y 0.0 6 y y 0.0 7 y z 0.0 8 y x 8.5 9 y z 0.0 10 n x 0.0 11 n z 0.0 12 n x 0.0 13 n x 0.0 14 n z 0.0 15 y x 8.5 16 n z 0.0 17 n z 0.0 18 n x 0.0 19 y y 0.0 asyncio.sleep()

来确定计时器
asyncio.ensure_future()

工作示例:

@asyncio.coroutine
def web_client_connected(self, websocket):
    self.web_client_socket = websocket

    while True:
        request = yield from self.web_client_socket.recv()
        json_val = process_request(request)
        asyncio.ensure_future(web_client_timer(json_val))
        yield

@asyncio.coroutine
def web_client_timer(self, json_val):
    yield from asyncio.sleep(60)
    yield from self.socket_queue.put(json_val)