Python twisted.internet.task.LoopingCall() Examples

The following are 30 code examples of twisted.internet.task.LoopingCall(). 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.task , or try the search function .
Example #1
Source File: wireprotocol.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def __init__(self, db, ip_address, nat_type, testnet=False, relaying=False):
        """
        Initialize the new protocol with the connection handler factory.

        Args:
                ip_address: a `tuple` of the (ip address, port) of ths node.
        """
        self.ip_address = ip_address
        self.testnet = testnet
        self.ws = None
        self.blockchain = None
        self.processors = []
        self.relay_node = None
        self.nat_type = nat_type
        self.vendors = db.vendors.get_vendors()
        self.ban_score = BanScore(self)
        self.factory = self.ConnHandlerFactory(self.processors, nat_type, self.relay_node, self.ban_score)
        self.log = Logger(system=self)
        self.keep_alive_loop = LoopingCall(self.keep_alive)
        self.keep_alive_loop.start(30, now=False)
        ConnectionMultiplexer.__init__(self, CryptoConnectionFactory(self.factory), self.ip_address[0], relaying) 
Example #2
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def loopUntil(predicate, interval=0):
    """
    Poor excuse for an event notification helper.  This polls a condition and
    calls back a Deferred when it is seen to be true.

    Do not use this function.
    """
    from twisted.internet import task
    d = defer.Deferred()
    def check():
        res = predicate()
        if res:
            d.callback(res)
    call = task.LoopingCall(check)
    def stop(result):
        call.stop()
        return result
    d.addCallback(stop)
    d2 = call.start(interval)
    d2.addErrback(d.errback)
    return d 
Example #3
Source File: carol.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def push_tx1(self):
        """Having seen TX0 confirmed, broadcast TX1 and wait for confirmation.
        """
        errmsg, success = self.tx1.push()
        if not success:
            return (False, "Failed to push TX1")
        #Monitor the output address of TX1 by importing
        cs_single().bc_interface.rpc("importaddress",
                            [self.tx1.output_address, "joinmarket-notify", False])
        #Wait until TX1 seen before confirming phase2 ready.
        self.loop = task.LoopingCall(self.check_for_phase1_utxos,
                                         [self.tx1.txid + ":" + str(
                                             self.tx1.pay_out_index)],
                                         self.receive_confirmation_tx_0_1)
        self.loop.start(3.0)
        return (True, "TX1 broadcast OK") 
Example #4
Source File: alice.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def send_tx4_sig(self):
        """Send partial signature on TX4 (out of TX0)
        to Carol for her to complete sign and broadcast.
        """
        utxo_in = self.tx0.txid + ":" + str(self.tx0.pay_out_index)
        self.tx4 = CoinSwapTX45.from_params(self.coinswap_parameters.pubkeys["key_2_2_AC_0"],
                                        self.coinswap_parameters.pubkeys["key_2_2_AC_1"],
                                        utxo_in=utxo_in,
                                        destination_address=self.coinswap_parameters.output_addresses["tx4_address"],
                                        destination_amount=self.coinswap_parameters.tx4_amounts["carol"],
                                        carol_change_address=None,
                                        carol_change_amount=None)
        self.tx4.sign_at_index(self.keyset["key_2_2_AC_0"][0], 0)
        sig = self.tx4.signatures[0][0]
        self.send(sig, self.tx5.txid)
        self.tx4broadcast_counter = 0
        self.loop_tx4 = task.LoopingCall(self.wait_for_tx4_confirmation)
        self.loop_tx4.start(3.0)
        return (True, "TX4 signature sent.") 
Example #5
Source File: network.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def __init__(self, node, db, signing_key, ksize=20, alpha=3, storage=None):
        """
        Create a server instance.  This will start listening on the given port.

        Args:
            node: The node instance for this peer. It must contain (at minimum) an ID,
                public key, ip address, and port.
            ksize (int): The k parameter from the paper
            alpha (int): The alpha parameter from the paper
            storage: An instance that implements :interface:`~dht.storage.IStorage`
        """
        self.ksize = ksize
        self.alpha = alpha
        self.log = Logger(system=self)
        self.storage = storage or ForgetfulStorage()
        self.node = node
        self.protocol = KademliaProtocol(self.node, self.storage, ksize, db, signing_key)
        self.refreshLoop = LoopingCall(self.refreshTable)
        reactor.callLater(1800, self.refreshLoop.start, 3600) 
Example #6
Source File: test_coinswap.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def runcase(alice_class, carol_class, fail_alice_state=None, fail_carol_state=None):
    options_server = Options()
    wallets = make_wallets(num_alices + 1,
                               wallet_structures=wallet_structures,
                               mean_amt=funding_amount)
    args_server = ["dummy"]
    test_data_server = (wallets[num_alices]['seed'], args_server, options_server,
                        False, None, carol_class, None, fail_carol_state)
    carol_bbmb = main_cs(test_data_server)
    options_alice = Options()
    options_alice.serve = False
    alices = []
    for i in range(num_alices):
        args_alice = ["dummy", amounts[i]]
        if dest_addr:
            args_alice.append(dest_addr)
        test_data_alice = (wallets[i]['seed'], args_alice, options_alice, False,
                           alice_class, None, fail_alice_state, None)
        alices.append(main_cs(test_data_alice))
    l = task.LoopingCall(miner)
    reactor.callWhenRunning(start_mining, l)
    reactor.run()
    return (alices, carol_bbmb, wallets[num_alices]['wallet']) 
Example #7
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_reset(self):
        """
        Test that L{LoopingCall} can be reset.
        """
        ran = []
        def foo():
            ran.append(None)

        c = task.Clock()
        lc = TestableLoopingCall(c, foo)
        lc.start(2, now=False)
        c.advance(1)
        lc.reset()
        c.advance(1)
        self.assertEqual(ran, [])
        c.advance(1)
        self.assertEqual(ran, [None]) 
Example #8
Source File: Refresh.py    From Timeline with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, penguin):
        self.penguin = penguin
        self.logger = logging.getLogger(TIMELINE_LOGGER)
        
        super(Refresh, self).__init__()

        self.logger.info("Penguin ASync-Refresh service initialized : Penguin - {}".format(self.penguin['nickname']))
        self.RefreshManagerLoop = LoopingCall(self._refresh)
        self.firstTimeCall = True
        self.CacheInitializedDefer = Deferred()
        self.cache = PenguinObject()

        self.penguin.penguin.data = self.cache # for easier access

        self.cacheHandlers = PenguinObject()

        self.logger.info("Penguin ASync-Refresh Loop started, every {}(s) : Penguin - {}".format
                         (self.REFRESH_INTERVAL, self.penguin['nickname']))

        self.RefreshManagerLoop.start(self.REFRESH_INTERVAL) 
Example #9
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_deferredDeprecation(self):
        """
        L{LoopingCall.deferred} is deprecated.
        """
        loop = task.LoopingCall(lambda: None)

        loop.deferred

        message = (
                'twisted.internet.task.LoopingCall.deferred was deprecated in '
                'Twisted 16.0.0; '
                'please use the deferred returned by start() instead'
                )
        warnings = self.flushWarnings([self.test_deferredDeprecation])
        self.assertEqual(1, len(warnings))
        self.assertEqual(DeprecationWarning, warnings[0]['category'])
        self.assertEqual(message, warnings[0]['message']) 
Example #10
Source File: services.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def configure_telemetry(update):
    global telemetry_looping_call

    hostConfig = update.cache_get('hostConfig')

    enabled = datastruct.getValue(hostConfig, 'telemetry.enabled', False)
    interval = datastruct.getValue(hostConfig, 'telemetry.interval', 60)

    # Cancel the old looping call.
    if telemetry_looping_call is not None:
        telemetry_looping_call.stop()
        telemetry_looping_call = None

    if enabled and interval > 0:
        telemetry_looping_call = LoopingCall(reporting.sendTelemetryReport)
        telemetry_looping_call.start(interval, now=False) 
Example #11
Source File: posixbase.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _checkLoop(self):
        """
        Start or stop a C{LoopingCall} based on whether there are readers and
        writers.
        """
        if self._readers or self._writers:
            if self._loop is None:
                from twisted.internet.task import LoopingCall, _EPSILON
                self._loop = LoopingCall(self.iterate)
                self._loop.clock = self._reactor
                # LoopingCall seems unhappy with timeout of 0, so use very
                # small number:
                self._loop.start(_EPSILON, now=False)
        elif self._loop:
            self._loop.stop()
            self._loop = None 
Example #12
Source File: docker_cleanup.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_cleanup_loop(ttl=1440, interval=30):
    # Check for valid values
    if ttl > 0 and interval > 0:
        # Convert to seconds
        secs = (interval * 60)
        # Create and start repeating cleanup timer
        t = task.LoopingCall(cleanup, ttl)
        t.start(secs) 
Example #13
Source File: client.py    From gpu-sentry with MIT License 5 votes vote down vote up
def run_client():
    """Run client to send statistics periodically."""
    l = task.LoopingCall(send_statistics)
    l.start(config.CLIENT_TIMEOUT)

    reactor.run() 
Example #14
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_reprFunction(self):
        """
        L{LoopingCall.__repr__} includes the wrapped function's name.
        """
        self.assertEqual(repr(task.LoopingCall(installReactor, 1, key=2)),
                         "LoopingCall<None>(installReactor, *(1,), **{'key': 2})") 
Example #15
Source File: _persistence.py    From flocker with Apache License 2.0 5 votes vote down vote up
def startService(self):
        self._lc = LoopingCall(self._expire)
        self._lc.clock = self._reactor
        self._lc.start(1) 
Example #16
Source File: _protocol.py    From flocker with Apache License 2.0 5 votes vote down vote up
def start(self, protocol, interval):
        """
        Start sending some pings.

        :param AMP protocol: The protocol over which to send the pings.
        :param timedelta interval: The interval at which to send the pings.
        """
        def ping():
            protocol.callRemote(NoOp)
        self._pinging = LoopingCall(ping)
        self._pinging.clock = self.reactor
        self._pinging.start(interval.total_seconds(), now=False) 
Example #17
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testBadDelay(self):
        lc = task.LoopingCall(lambda: None)
        self.assertRaises(ValueError, lc.start, -1)


    # Make sure that LoopingCall.stop() prevents any subsequent calls. 
Example #18
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_withCountIntervalZeroDelayThenNonZeroInterval(self):
        """
        L{task.LoopingCall.withCount} with interval set to 0 will still keep
        the time when last called so when the interval is reset.
        """
        clock = task.Clock()
        deferred = defer.Deferred()
        accumulator = []

        def foo(cnt):
            accumulator.append(cnt)
            if len(accumulator) == 2:
                return deferred

        loop = task.LoopingCall.withCount(foo)
        loop.clock = clock
        loop.start(0, now=False)

        # Even if a lot of time pass, loop will block at the third call.
        clock.advance(10)
        self.assertEqual([1, 1], accumulator)

        # When a new interval is set, once the waiting call got a result the
        # loop continues with the new interval.
        loop.interval = 2
        deferred.callback(None)

        # It will count skipped steps since the last loop call.
        clock.advance(7)
        self.assertEqual([1, 1, 3], accumulator)

        clock.advance(2)
        self.assertEqual([1, 1, 3, 1], accumulator)

        clock.advance(4)
        self.assertEqual([1, 1, 3, 1, 2], accumulator) 
Example #19
Source File: test_api.py    From flocker with Apache License 2.0 5 votes vote down vote up
def initialize(self):
        """
        Create initial objects for the ``VolumePlugin``.
        """
        self.volume_plugin_reactor = Clock()
        self.flocker_client = SimpleCountingProxy(FakeFlockerClient())
        # The conditional_create operation used by the plugin relies on
        # the passage of time... so make sure time passes! We still use a
        # fake clock since some tests want to skip ahead.
        self.looping = LoopingCall(
            lambda: self.volume_plugin_reactor.advance(0.001))
        self.looping.start(0.001)
        self.addCleanup(self.looping.stop) 
Example #20
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testStopAtOnceLater(self):
        # Ensure that even when LoopingCall.stop() is called from a
        # reactor callback, it still prevents any subsequent calls.
        d = defer.Deferred()
        def foo():
            d.errback(failure.DefaultException(
                "This task also should never get called."))
        self._lc = task.LoopingCall(foo)
        self._lc.start(1, now=False)
        reactor.callLater(0, self._callback_for_testStopAtOnceLater, d)
        return d 
Example #21
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_withCountIntervalZeroDelay(self):
        """
        L{task.LoopingCall.withCount} with interval set to 0 and a delayed
        call during the loop run will still call the countCallable 1 as if
        no delay occurred.
        """
        clock = task.Clock()
        deferred = defer.Deferred()
        accumulator = []

        def foo(cnt):
            accumulator.append(cnt)

            if len(accumulator) == 2:
                return deferred

            if len(accumulator) > 4:
                loop.stop()

        loop = task.LoopingCall.withCount(foo)
        loop.clock = clock
        loop.start(0, now=False)

        clock.advance(0)
        # Loop will block at the third call.
        self.assertEqual([1, 1], accumulator)

        # Even if more time pass, the loops is not
        # advanced.
        clock.advance(2)
        self.assertEqual([1, 1], accumulator)

        # Once the waiting call got a result the loop continues without
        # observing any delay in countCallable.
        deferred.callback(None)
        clock.advance(0)
        self.assertEqual([1, 1, 1, 1, 1], accumulator) 
Example #22
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_countLengthyIntervalCounts(self):
        """
        L{LoopingCall.withCount} counts only calls that were expected to be
        made.  So, if more than one, but less than two intervals pass between
        invocations, it won't increase the count above 1.  For example, a
        L{LoopingCall} with interval T expects to be invoked at T, 2T, 3T, etc.
        However, the reactor takes some time to get around to calling it, so in
        practice it will be called at T+something, 2T+something, 3T+something;
        and due to other things going on in the reactor, "something" is
        variable.  It won't increase the count unless "something" is greater
        than T.  So if the L{LoopingCall} is invoked at T, 2.75T, and 3T,
        the count has not increased, even though the distance between
        invocation 1 and invocation 2 is 1.75T.
        """
        times = []
        clock = task.Clock()
        def aCallback(count):
            times.append((clock.seconds(), count))

        # Start a LoopingCall that tracks the time passed, and the number of
        # calls, with a 0.5 second increment.
        call = task.LoopingCall.withCount(aCallback)
        call.clock = clock
        INTERVAL = 0.5
        REALISTIC_DELAY = 0.01
        call.start(INTERVAL)
        self.assertEqual(times.pop(), (0, 1))

        # About one interval... So far, so good
        clock.advance(INTERVAL + REALISTIC_DELAY)
        self.assertEqual(times.pop(), (INTERVAL + REALISTIC_DELAY, 1))

        # Oh no, something delayed us for a while.
        clock.advance(INTERVAL * 1.75)
        self.assertEqual(times.pop(), ((2.75 * INTERVAL) + REALISTIC_DELAY, 1))

        # Back on track!  We got invoked when we expected this time.
        clock.advance(INTERVAL * 0.25)
        self.assertEqual(times.pop(), ((3.0 * INTERVAL) + REALISTIC_DELAY, 1)) 
Example #23
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_reactorTimeSkips(self):
        """
        When more time than the defined interval passes between when
        L{LoopingCall} schedules itself to run again and when it actually
        runs again, it should schedule the next call for the next interval
        which is still in the future.
        """
        times = []
        clock = task.Clock()
        def aCallback():
            times.append(clock.seconds())

        # Start a LoopingCall that tracks the time passed, with a 0.5 second
        # increment.
        call = task.LoopingCall(aCallback)
        call.clock = clock
        call.start(0.5)

        # Initially, no time should have passed!
        self.assertEqual(times, [0])

        # Advance the clock by 2 seconds (2 seconds should have passed)
        clock.advance(2)
        self.assertEqual(times, [0, 2])

        # Advance the clock by 1 second (3 total should have passed)
        clock.advance(1)
        self.assertEqual(times, [0, 2, 3])

        # Advance the clock by 0 seconds (this should have no effect!)
        clock.advance(0)
        self.assertEqual(times, [0, 2, 3]) 
Example #24
Source File: conch.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, conn):
        self.conn = conn
        self.globalTimeout = None
        self.lc = task.LoopingCall(self.sendGlobal)
        self.lc.start(300) 
Example #25
Source File: test_conch.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def openShell(self, transport):
        """
        Write 60 lines of data to the transport, then exit.
        """
        proto = protocol.Protocol()
        proto.makeConnection(transport)
        transport.makeConnection(wrapProtocol(proto))

        # Send enough bytes to the connection so that a rekey is triggered in
        # the client.
        def write(counter):
            i = next(counter)
            if i == 60:
                call.stop()
                transport.session.conn.sendRequest(
                    transport.session, b'exit-status', b'\x00\x00\x00\x00')
                transport.loseConnection()
            else:
                line = "line #%02d\n" % (i,)
                line = line.encode("utf-8")
                transport.write(line)

        # The timing for this loop is an educated guess (and/or the result of
        # experimentation) to exercise the case where a packet is generated
        # mid-rekey.  Since the other side of the connection is (so far) the
        # OpenSSH command line client, there's no easy way to determine when the
        # rekey has been initiated.  If there were, then generating a packet
        # immediately at that time would be a better way to test the
        # functionality being tested here.
        call = LoopingCall(write, count())
        call.start(0.01) 
Example #26
Source File: secondary.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def startService(self):
        service.Service.startService(self)
        self.calls = [task.LoopingCall(d.transfer) for d in self.domains]
        i = 0
        from twisted.internet import reactor
        for c in self.calls:
            # XXX Add errbacks, respect proper timeouts
            reactor.callLater(i, c.start, 60 * 60)
            i += 1 
Example #27
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_startServiceUsesGlobalReactor(self):
        """
        L{TimerService.startService} uses L{internet._maybeGlobalReactor} to
        choose the reactor to pass to L{task.LoopingCall}
        uses the global reactor.
        """
        otherClock = task.Clock()
        def getOtherClock(maybeReactor):
            return otherClock
        self.patch(internet, "_maybeGlobalReactor", getOtherClock)
        self.timer.startService()
        self.assertIdentical(otherClock, self.timer._loop.clock) 
Example #28
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_startService(self):
        """
        When L{TimerService.startService} is called, it marks itself
        as running, creates a L{task.LoopingCall} and starts it.
        """
        self.timer.startService()
        self.assertTrue(self.timer.running, "Service is started")
        self.assertIsInstance(self.timer._loop, task.LoopingCall)
        self.assertIdentical(self.clock, self.timer._loop.clock)
        self.assertTrue(self.timer._loop.running, "LoopingCall is started") 
Example #29
Source File: internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def startService(self):
        service.Service.startService(self)
        callable, args, kwargs = self.call
        # we have to make a new LoopingCall each time we're started, because
        # an active LoopingCall remains active when serialized. If
        # LoopingCall were a _VolatileDataService, we wouldn't need to do
        # this.
        self._loop = task.LoopingCall(callable, *args, **kwargs)
        self._loop.clock = _maybeGlobalReactor(self.clock)
        self._loopFinished = self._loop.start(self.step, now=True)
        self._loopFinished.addErrback(self._failed) 
Example #30
Source File: tksupport.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def install(widget, ms=10, reactor=None):
    """Install a Tkinter.Tk() object into the reactor."""
    installTkFunctions()
    global _task
    _task = task.LoopingCall(widget.update)
    _task.start(ms / 1000.0, False)