0

I am using sleekxmpp as the xmpp client for python. The requests are coming which I am further forwarding to other users/agents.
Now the use case is, if a user is not available we need to check the availability every 10 seconds and transfer to him when he is available. We need to send a message to customer only 5 times but check the availability for a long time.

I am using time.sleep() if the user is not available to check again in 10 seconds, but the problem is it is blocking the entire thread and no new requests are coming to the server.

send_msg_counter = 0
check_status = False
while not check_status:
    check_status = requests.post(transfer_chat_url, data=data)
    if send_msg_counter < 5:
        send_msg("please wait", customer)
        send_msg_counter += 1
    time.sleep(10)
4

2 回答 2

1

这确实time.sleep(10)会阻止您的活动线程。您实际上可能会发现使用 Python 3 的 async/await 是可行的方法。遗憾的是,我对这些关键字还没有太多经验,但另一条路线可能是实现 python 的线程。

https://docs.python.org/3/library/threading.html

这可能是实现此功能的一种方法。

import threading

def poll_counter(customer, transfer_chat_url, data, send_count=5, interval=10):
    send_msg_counter = 0
    check_status = False
    while not check_status:
        check_status = requests.post(transfer_chat_url, data=data)
        if send_msg_counter < send_count:
            send_msg("please wait", customer)
            send_msg_counter += 1
        time.sleep(interval)

    # If we're here, check status became true
    return None

... pre-existing code ...
threading.Thread(target=poll_counter, args=(customer, transfer_chat_url, data)).start()

... proceed to handle other tasks while the thread runs in the background.

现在,我不会详细介绍,但在某些用例中,线程是一个重大错误。这不应该是其中之一,但这是一本很好的读物,可让您了解这些用例。 https://realpython.com/python-gil/

此外,有关 asyncio (async/await) 的更多详细信息,这里是一个很好的资源。 https://docs.python.org/3/library/asyncio-task.html

于 2019-09-28T06:22:43.547 回答
1

尝试实施

        delay = min(self.reconnect_delay * 2, self.reconnect_max_delay)
        delay = random.normalvariate(delay, delay * 0.1)
        log.debug('Waiting %s seconds before connecting.', delay)
        elapsed = 0
        try:
            while elapsed < delay and not self.stop.is_set():
                time.sleep(0.1)
                elapsed += 0.1
        except KeyboardInterrupt:
            self.set_stop()
            return False
        except SystemExit:
            self.set_stop()
            return False

来源链接

于 2019-09-28T06:28:36.170 回答