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)
sid8491
  • 6,622
  • 6
  • 38
  • 64

2 Answers2

1

This is true that time.sleep(10) will block your active thread. You may actually find that using Python 3's async/await to be the way to go. Sadly I don't have much experience with those keywords yet, but another route might be to implement python's threading.

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

Here might be one way to implement this feature.

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.

Now, I won't go into detail, but there are use cases where threading is a major mistake. This shouldn't be one of them, but here is a good read for you to understand those use cases. https://realpython.com/python-gil/

Also, for more details on asyncio (async/await) here is a good resource. https://docs.python.org/3/library/asyncio-task.html

Kamori
  • 356
  • 1
  • 9
1

Try implementing

        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

Source Link

champion-runner
  • 1,489
  • 1
  • 13
  • 26