Skip to content

Handlers Cannot Terminate Connection #31

Description

@alexmbird

I'm trying to write some code that'll handle a fixed number of events then exit. The natural way to do this seems to be calling Pusher.disconnect() from a handler once it's seen enough events.

But since the callbacks are fired from within Pusher's connection thread and disconnect() ends in a Thread.join(), this results in a RuntimeError.

Example code:

import time
import pusherclient

class MyClient(object):
    
    STOP_AT_N = 5
    
    def __init__(self):
        super(MyClient,self).__init__()
        self.n_events = 0
    
    def connect(self):
        "Connect to a random Pusher channel & consume events"
        self.pusher = pusherclient.Pusher('de504dc5763aeef9ff52')
        def event_handler(e):
            self.n_events += 1
            print("event %d" % (self.n_events,))
            if self.n_events >= self.STOP_AT_N:
                self.pusher.disconnect()
        def connect_handler(data):
            channel = self.pusher.subscribe('live_orders')
            channel.bind('order_created', event_handler)
        self.pusher.connection.bind('pusher:connection_established', connect_handler)
        self.pusher.connect()


if __name__ == '__main__':
    mc = MyClient()
    mc.connect()
    while True:
        time.sleep(1)

What happens for me:

$ python3 experiments/pusher_handler_disconnect.py
event 1
event 2
event 3
event 4
event 5
error from callback <bound method Connection._on_message of <Connection(Thread-1, started daemon 123145422946304)>>: cannot join current thread

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions