Python twisted.internet.reactor.getDelayedCalls() Examples

The following are 28 code examples of twisted.internet.reactor.getDelayedCalls(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.reactor , or try the search function .
Example #1
Source File: test_http2.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_initiallySchedulesOneDataCall(self):
        """
        When a H2Connection is established it schedules one call to be run as
        soon as the reactor has time.
        """
        reactor = task.Clock()
        a = H2Connection(reactor)

        calls = reactor.getDelayedCalls()
        self.assertEqual(len(calls), 1)
        call = calls[0]

        # Validate that the call is scheduled for right now, but hasn't run,
        # and that it's correct.
        self.assertTrue(call.active())
        self.assertEqual(call.time, 0)
        self.assertEqual(call.func, a._sendPrioritisedData)
        self.assertEqual(call.args, ())
        self.assertEqual(call.kw, {}) 
Example #2
Source File: test_internet.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testGetDelayedCalls(self):
        if not hasattr(reactor, "getDelayedCalls"):
            return
        # This is not a race because we don't do anything which might call
        # the reactor until we have all the timers set up. If we did, this
        # test might fail on slow systems.
        self.checkTimers()
        self.addTimer(35, self.done)
        self.addTimer(20, self.callback)
        self.addTimer(30, self.callback)
        which = self.counter
        self.addTimer(29, self.callback)
        self.addTimer(25, self.addCallback)
        self.addTimer(26, self.callback)

        self.timers[which].cancel()
        del self.timers[which]
        self.checkTimers()

        self.deferred.addCallback(lambda x : self.checkTimers())
        return self.deferred 
Example #3
Source File: util.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def do_cleanPending(cls):
        # don't import reactor when module is loaded
        from twisted.internet import reactor

        # flush short-range timers
        reactor.iterate(0)
        reactor.iterate(0)

        pending = reactor.getDelayedCalls()
        if pending:
            s = PENDING_TIMED_CALLS_MSG
            for p in pending:
                s += " %s\n" % (p,)
                if p.active():
                    p.cancel() # delete the rest
                else:
                    print "WEIRNESS! pending timed call not active+!"
            raise PendingTimedCallsError(s) 
Example #4
Source File: test_internet.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testGetDelayedCalls(self):
        if not hasattr(reactor, "getDelayedCalls"):
            return
        # This is not a race because we don't do anything which might call
        # the reactor until we have all the timers set up. If we did, this
        # test might fail on slow systems.
        self.checkTimers()
        self.addTimer(35, self.done)
        self.addTimer(20, self.callback)
        self.addTimer(30, self.callback)
        which = self.counter
        self.addTimer(29, self.callback)
        self.addTimer(25, self.addCallback)
        self.addTimer(26, self.callback)

        self.timers[which].cancel()
        del self.timers[which]
        self.checkTimers()

        self.deferred.addCallback(lambda x : self.checkTimers())
        return self.deferred 
Example #5
Source File: util.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _cleanPending(self):
        """
        Cancel all pending calls and return their string representations.
        """
        reactor = self._getReactor()

        # flush short-range timers
        reactor.iterate(0)
        reactor.iterate(0)

        delayedCallStrings = []
        for p in reactor.getDelayedCalls():
            if p.active():
                delayedString = str(p)
                p.cancel()
            else:
                print "WEIRDNESS! pending timed call not active!"
            delayedCallStrings.append(delayedString)
        return delayedCallStrings 
Example #6
Source File: test_internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testGetDelayedCalls(self):
        if not hasattr(reactor, "getDelayedCalls"):
            return
        # This is not a race because we don't do anything which might call
        # the reactor until we have all the timers set up. If we did, this
        # test might fail on slow systems.
        self.checkTimers()
        self.addTimer(35, self.done)
        self.addTimer(20, self.callback)
        self.addTimer(30, self.callback)
        which = self.counter
        self.addTimer(29, self.callback)
        self.addTimer(25, self.addCallback)
        self.addTimer(26, self.callback)

        self.timers[which].cancel()
        del self.timers[which]
        self.checkTimers()

        self.deferred.addCallback(lambda x : self.checkTimers())
        return self.deferred 
Example #7
Source File: test_internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def checkTimers(self):
        l1 = self.timers.values()
        l2 = list(reactor.getDelayedCalls())

        # There should be at least the calls we put in.  There may be other
        # calls that are none of our business and that we should ignore,
        # though.

        missing = []
        for dc in l1:
            if dc not in l2:
                missing.append(dc)
        if missing:
            self.finished = 1
        self.assertFalse(missing, "Should have been missing no calls, instead "
                         + "was missing " + repr(missing)) 
Example #8
Source File: util.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _cleanPending(self):
        """
        Cancel all pending calls and return their string representations.
        """
        reactor = self._getReactor()

        # flush short-range timers
        reactor.iterate(0)
        reactor.iterate(0)

        delayedCallStrings = []
        for p in reactor.getDelayedCalls():
            if p.active():
                delayedString = str(p)
                p.cancel()
            else:
                print("WEIRDNESS! pending timed call not active!")
            delayedCallStrings.append(delayedString)
        return delayedCallStrings 
Example #9
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testGetDelayedCalls(self):
        if not hasattr(reactor, "getDelayedCalls"):
            return
        # This is not a race because we don't do anything which might call
        # the reactor until we have all the timers set up. If we did, this
        # test might fail on slow systems.
        self.checkTimers()
        self.addTimer(35, self.done)
        self.addTimer(20, self.callback)
        self.addTimer(30, self.callback)
        which = self.counter
        self.addTimer(29, self.callback)
        self.addTimer(25, self.addCallback)
        self.addTimer(26, self.callback)

        self.timers[which].cancel()
        del self.timers[which]
        self.checkTimers()

        self.deferred.addCallback(lambda x : self.checkTimers())
        return self.deferred 
Example #10
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def checkTimers(self):
        l1 = self.timers.values()
        l2 = list(reactor.getDelayedCalls())

        # There should be at least the calls we put in.  There may be other
        # calls that are none of our business and that we should ignore,
        # though.

        missing = []
        for dc in l1:
            if dc not in l2:
                missing.append(dc)
        if missing:
            self.finished = 1
        self.assertFalse(missing, "Should have been missing no calls, instead "
                         + "was missing " + repr(missing)) 
Example #11
Source File: util.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _cleanPending(self):
        """
        Cancel all pending calls and return their string representations.
        """
        reactor = self._getReactor()

        # flush short-range timers
        reactor.iterate(0)
        reactor.iterate(0)

        delayedCallStrings = []
        for p in reactor.getDelayedCalls():
            if p.active():
                delayedString = str(p)
                p.cancel()
            else:
                print("WEIRDNESS! pending timed call not active!")
            delayedCallStrings.append(delayedString)
        return delayedCallStrings 
Example #12
Source File: test_http2.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_initiallySchedulesOneDataCall(self):
        """
        When a H2Connection is established it schedules one call to be run as
        soon as the reactor has time.
        """
        reactor = task.Clock()
        a = H2Connection(reactor)

        calls = reactor.getDelayedCalls()
        self.assertEqual(len(calls), 1)
        call = calls[0]

        # Validate that the call is scheduled for right now, but hasn't run,
        # and that it's correct.
        self.assertTrue(call.active())
        self.assertEqual(call.time, 0)
        self.assertEqual(call.func, a._sendPrioritisedData)
        self.assertEqual(call.args, ())
        self.assertEqual(call.kw, {}) 
Example #13
Source File: twistedtools.py    From Computable with MIT License 6 votes vote down vote up
def stop_reactor():
    """Stop the reactor and join the reactor thread until it stops.
    Call this function in teardown at the module or package level to
    reset the twisted system after your tests. You *must* do this if
    you mix tests using these tools and tests using twisted.trial.
    """
    global _twisted_thread

    def stop_reactor():
        '''Helper for calling stop from withing the thread.'''
        reactor.stop()

    reactor.callFromThread(stop_reactor)
    reactor_thread.join()
    for p in reactor.getDelayedCalls():
        if p.active():
            p.cancel()
    _twisted_thread = None 
Example #14
Source File: twistedtools.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def stop_reactor():
    """Stop the reactor and join the reactor thread until it stops.
    Call this function in teardown at the module or package level to
    reset the twisted system after your tests. You *must* do this if
    you mix tests using these tools and tests using twisted.trial.
    """
    global _twisted_thread

    def stop_reactor():
        '''Helper for calling stop from withing the thread.'''
        reactor.stop()

    reactor.callFromThread(stop_reactor)
    reactor_thread.join()
    for p in reactor.getDelayedCalls():
        if p.active():
            p.cancel()
    _twisted_thread = None 
Example #15
Source File: test_client_protocol.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        for dc in reactor.getDelayedCalls():
            dc.cancel() 
Example #16
Source File: test_client_protocol.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        for dc in reactor.getDelayedCalls():
            dc.cancel() 
Example #17
Source File: runtest.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _cleanPending(self):
        """Cancel all pending calls and return their string representations.

        Delayed calls belonging to crochet and twisted internals are ignored.
        """
        for call in reactor.getDelayedCalls():
            if call.active() and not call_belongs_to_internals(call):
                yield call
                call.cancel() 
Example #18
Source File: test_taker.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def setup_taker(request):
    def clean():
        from twisted.internet import reactor
        for dc in reactor.getDelayedCalls():
            dc.cancel()
    request.addfinalizer(clean)
    def cmtdatateardown():
        shutil.rmtree("cmtdata")
    request.addfinalizer(cmtdatateardown)
    if not os.path.exists("cmtdata"):
            os.makedirs("cmtdata")
    load_test_config()
    jm_single().bc_interface = DummyBlockchainInterface()
    jm_single().config.set("BLOCKCHAIN", "network", "testnet") 
Example #19
Source File: test_coinjoin.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def setup_cj():
    load_test_config()
    jm_single().config.set('POLICY', 'tx_broadcast', 'self')
    jm_single().bc_interface.tick_forward_chain_interval = 5
    jm_single().bc_interface.simulate_blocks()
    yield None
    # teardown
    for dc in reactor.getDelayedCalls():
        dc.cancel() 
Example #20
Source File: test_payjoin.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def setup_cj():
    load_test_config()
    jm_single().config.set('POLICY', 'tx_broadcast', 'self')
    jm_single().bc_interface.tick_forward_chain_interval = 5
    jm_single().bc_interface.simulate_blocks()
    #see note in cryptoengine.py:
    cryptoengine.BTC_P2WPKH.VBYTE = 100
    yield None
    # teardown
    for dc in reactor.getDelayedCalls():
        dc.cancel() 
Example #21
Source File: test_internet.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def checkTimers(self):
        l1 = self.timers.values()
        l2 = list(reactor.getDelayedCalls())

        # There should be at least the calls we put in.  There may be other
        # calls that are none of our business and that we should ignore,
        # though.

        missing = []
        for dc in l1:
            if dc not in l2:
                missing.append(dc)
        if missing:
            self.finished = 1
        self.failIf(missing, "Should have been missing no calls, instead was missing " + repr(missing)) 
Example #22
Source File: test_internet.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.finished = 0
        self.counter = 0
        self.timers = {}
        self.deferred = defer.Deferred()
        # ick. Sometimes there are magic timers already running:
        # popsicle.Freezer.tick . Kill off all such timers now so they won't
        # interfere with the test. Of course, this kind of requires that
        # getDelayedCalls already works, so certain failure modes won't be
        # noticed.
        if not hasattr(reactor, "getDelayedCalls"):
            return
        for t in reactor.getDelayedCalls():
            t.cancel()
        reactor.iterate() # flush timers 
Example #23
Source File: test_internet.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def checkTimers(self):
        l1 = self.timers.values()
        l2 = list(reactor.getDelayedCalls())

        # There should be at least the calls we put in.  There may be other
        # calls that are none of our business and that we should ignore,
        # though.

        missing = []
        for dc in l1:
            if dc not in l2:
                missing.append(dc)
        if missing:
            self.finished = 1
        self.failIf(missing, "Should have been missing no calls, instead was missing " + repr(missing)) 
Example #24
Source File: test_http2.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_noTimeoutIfConnectionLost(self):
        """
        When a L{H2Connection} loses its connection it cancels its timeout.
        """
        frameFactory = FrameFactory()
        frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory)
        initialData = frameFactory.clientConnectionPreface()
        initialData += b''.join(f.serialize() for f in frames)

        reactor, conn, transport = self.initiateH2Connection(
            initialData, requestFactory=DummyProducerHandler,
        )

        sentData = transport.value()
        oldCallCount = len(reactor.getDelayedCalls())

        # Now lose the connection.
        conn.connectionLost("reason")

        # There should be one fewer call than there was.
        currentCallCount = len(reactor.getDelayedCalls())
        self.assertEqual(oldCallCount - 1, currentCallCount)

        # Advancing the clock should do nothing.
        reactor.advance(101)
        self.assertEqual(transport.value(), sentData) 
Example #25
Source File: protocols.py    From pade with MIT License 5 votes vote down vote up
def handle_refuse(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_REFUSE type message 

            :param message: FIPA-ACL message
        """
        self.received_qty += 1
        print_progress_bar(self.received_qty, self.cfp_qty, fill='#', length=50, prefix='CFP responses received')
        if self.received_qty == self.cfp_qty:
            pass
            # delayed_calls = reactor.getDelayedCalls()
            # for call in delayed_calls:
            #     call.cancel() 
Example #26
Source File: protocols.py    From pade with MIT License 5 votes vote down vote up
def handle_propose(self, message):
        """This method should be overridden when implementing a protocol.
            This method is always executed when the agent receives a 
            FIPA_PROPOSE type message 

            :param message: FIPA-ACL message
        """
        self.received_qty += 1
        print_progress_bar(self.received_qty, self.cfp_qty, fill='#', length=50, prefix='CFP responses received')
        if self.received_qty == self.cfp_qty:
            pass
            # delayed_calls = reactor.getDelayedCalls()
            # for call in delayed_calls:
            #     call.cancel() 
Example #27
Source File: test_http2.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_noTimeoutIfConnectionLost(self):
        """
        When a L{H2Connection} loses its connection it cancels its timeout.
        """
        frameFactory = FrameFactory()
        frames = buildRequestFrames(self.getRequestHeaders, [], frameFactory)
        initialData = frameFactory.clientConnectionPreface()
        initialData += b''.join(f.serialize() for f in frames)

        reactor, conn, transport = self.initiateH2Connection(
            initialData, requestFactory=DummyProducerHandler,
        )

        sentData = transport.value()
        oldCallCount = len(reactor.getDelayedCalls())

        # Now lose the connection.
        conn.connectionLost("reason")

        # There should be one fewer call than there was.
        currentCallCount = len(reactor.getDelayedCalls())
        self.assertEqual(oldCallCount - 1, currentCallCount)

        # Advancing the clock should do nothing.
        reactor.advance(101)
        self.assertEqual(transport.value(), sentData) 
Example #28
Source File: mig.py    From kotori with GNU Affero General Public License v3.0 4 votes vote down vote up
def process_metrics(self):

        metrics = []

        # Compute frequency of measurements
        if 'packet_time' in self.metrics and self.metrics['packet_time'] is not None:

            self.metrics.setdefault('packet_starttime', self.metrics.packet_time)

            # Convert nanos to seconds
            packet_duration = (self.metrics.packet_time - self.metrics.packet_starttime) / 1000.0 / 1000.0 / 1000.0
            packet_duration = packet_duration or self.metrics.starttime
            if packet_duration != 0:
                packet_frequency = self.metrics.tx_count / float(packet_duration)
            else:
                packet_frequency = 0.0

            metrics.append('measurements: %.02f Hz' % packet_frequency)

            # Reset for next round
            self.metrics.packet_starttime = self.metrics.packet_time

        # Compute frequency of transactions
        now = time.time()
        transaction_duration = now - self.metrics.starttime
        if transaction_duration != 0:
            transaction_frequency = self.metrics.tx_count / float(transaction_duration)
        else:
            transaction_frequency = 0.0
        metrics.append('transactions: %.02f tps' % transaction_frequency)

        # Reset for next round
        self.metrics.tx_count = 0
        self.metrics.starttime = now


        # Add information from the Twisted reactor
        pending_calls = reactor.getDelayedCalls()
        pending_count = len(pending_calls)
        #metrics.append('pending: %d' % pending_count)

        metrics_info = ', '.join(metrics)

        log.info('[{realm:12s}] {metrics_info}', realm=self.channel.realm, metrics_info=metrics_info)