Python twisted.application.internet.TimerService() Examples

The following are 30 code examples of twisted.application.internet.TimerService(). 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.application.internet , or try the search function .
Example #1
Source File: _twistw.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def runApp(config):
    passphrase = app.getPassphrase(config['encrypted'])
    app.installReactor(config['reactor'])
    application = app.getApplication(config, passphrase)
    oldstdout = sys.stdout
    oldstderr = sys.stderr
    startLogging(config['logfile'])
    app.initialLog()
    os.chdir(config['rundir'])
    service.IService(application).privilegedStartService()
    app.startApplication(application, not config['no_save'])
    app.startApplication(internet.TimerService(0.1, lambda:None), 0)
    app.runReactorWithLogging(config, oldstdout, oldstderr)
    app.reportProfile(config['report-profile'],
                      service.IProcess(application).processName)
    log.msg("Server Shut Down.") 
Example #2
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testTimerRestart(self):
        # restart the same TimerService
        d1 = defer.Deferred()
        d2 = defer.Deferred()
        work = [(d2, "bar"), (d1, "foo")]
        def trigger():
            d, arg = work.pop()
            d.callback(arg)
        self.t = internet.TimerService(1, trigger)
        self.t.startService()
        def onFirstResult(result):
            self.assertEqual(result, 'foo')
            return self.t.stopService()
        def onFirstStop(ignored):
            self.assertFalse(self.t.running)
            self.t.startService()
            return d2
        def onSecondResult(result):
            self.assertEqual(result, 'bar')
            self.t.stopService()
        d1.addCallback(onFirstResult)
        d1.addCallback(onFirstStop)
        d1.addCallback(onSecondResult)
        return d1 
Example #3
Source File: test_application.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testTimerRestart(self):
        # restart the same TimerService
        d1 = defer.Deferred()
        d2 = defer.Deferred()
        work = [(d2, "bar"), (d1, "foo")]
        def trigger():
            d, arg = work.pop()
            d.callback(arg)
        self.t = internet.TimerService(1, trigger)
        self.t.startService()
        def onFirstResult(result):
            self.assertEqual(result, 'foo')
            return self.t.stopService()
        def onFirstStop(ignored):
            self.failIf(self.t.running)
            self.t.startService()
            return d2
        def onSecondResult(result):
            self.assertEqual(result, 'bar')
            self.t.stopService()
        d1.addCallback(onFirstResult)
        d1.addCallback(onFirstStop)
        d1.addCallback(onSecondResult)
        return d1 
Example #4
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testTimerRestart(self):
        # restart the same TimerService
        d1 = defer.Deferred()
        d2 = defer.Deferred()
        work = [(d2, "bar"), (d1, "foo")]
        def trigger():
            d, arg = work.pop()
            d.callback(arg)
        self.t = internet.TimerService(1, trigger)
        self.t.startService()
        def onFirstResult(result):
            self.assertEqual(result, 'foo')
            return self.t.stopService()
        def onFirstStop(ignored):
            self.failIf(self.t.running)
            self.t.startService()
            return d2
        def onSecondResult(result):
            self.assertEqual(result, 'bar')
            self.t.stopService()
        d1.addCallback(onFirstResult)
        d1.addCallback(onFirstStop)
        d1.addCallback(onSecondResult)
        return d1 
Example #5
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testTimerRestart(self):
        # restart the same TimerService
        d1 = defer.Deferred()
        d2 = defer.Deferred()
        work = [(d2, "bar"), (d1, "foo")]
        def trigger():
            d, arg = work.pop()
            d.callback(arg)
        self.t = internet.TimerService(1, trigger)
        self.t.startService()
        def onFirstResult(result):
            self.assertEqual(result, 'foo')
            return self.t.stopService()
        def onFirstStop(ignored):
            self.assertFalse(self.t.running)
            self.t.startService()
            return d2
        def onSecondResult(result):
            self.assertEqual(result, 'bar')
            self.t.stopService()
        d1.addCallback(onFirstResult)
        d1.addCallback(onFirstStop)
        d1.addCallback(onSecondResult)
        return d1 
Example #6
Source File: tftp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, resource_root, port, client_service):
        """
        :param resource_root: The root directory for this TFTP server.
        :param port: The port on which each server should be started.
        :param client_service: The RPC client service for the rack controller.
        """
        super().__init__()
        self.backend = TFTPBackend(resource_root, client_service)
        self.port = port
        # Establish a periodic call to self.updateServers() every 45
        # seconds, so that this service eventually converges on truth.
        # TimerService ensures that a call is made to it's target
        # function immediately as it's started, so there's no need to
        # call updateServers() from here.
        self.refresher = internet.TimerService(45, self.updateServers)
        self.refresher.setName("refresher")
        self.refresher.setServiceParent(self) 
Example #7
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBrokenTimer(self):
        d = defer.Deferred()
        t = internet.TimerService(1, lambda: 1 / 0)
        oldFailed = t._failed
        def _failed(why):
            oldFailed(why)
            d.callback(None)
        t._failed = _failed
        t.startService()
        d.addCallback(lambda x : t.stopService)
        d.addCallback(lambda x : self.assertEqual(
            [ZeroDivisionError],
            [o.value.__class__ for o in log.flushErrors(ZeroDivisionError)]))
        return d 
Example #8
Source File: twisted.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
def _get_non_api_monitor(self, service):
        return service.get_monitor_thread(monitor_thread_wrapper=lambda target, kwargs: TimerService(1, target, **kwargs)) 
Example #9
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testTimerLoops(self):
        l = []
        def trigger(data, number, d):
            l.append(data)
            if len(l) == number:
                d.callback(l)
        d = defer.Deferred()
        self.t = internet.TimerService(0.01, trigger, "hello", 10, d)
        self.t.startService()
        d.addCallback(self.assertEqual, ['hello'] * 10)
        d.addCallback(lambda x : self.t.stopService())
        return d 
Example #10
Source File: _twistw.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def postApplication(self):
        """
        Start the application and run the reactor.
        """
        service.IService(self.application).privilegedStartService()
        app.startApplication(self.application, not self.config['no_save'])
        app.startApplication(internet.TimerService(0.1, lambda:None), 0)
        self.startReactor(None, self.oldstdout, self.oldstderr)
        log.msg("Server Shut Down.") 
Example #11
Source File: relaymanager.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def RelayStateHelper(manager, delay):
    return internet.TimerService(delay, _checkState, manager) 
Example #12
Source File: test_application.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testPickledTimer(self):
        target = TimerTarget()
        t0 = internet.TimerService(1, target.append, "hello")
        t0.startService()
        s = pickle.dumps(t0)
        t0.stopService()

        t = pickle.loads(s)
        self.failIf(t.running) 
Example #13
Source File: test_application.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testBrokenTimer(self):
        d = defer.Deferred()
        t = internet.TimerService(1, lambda: 1 / 0)
        oldFailed = t._failed
        def _failed(why):
            oldFailed(why)
            d.callback(None)
        t._failed = _failed
        t.startService()
        d.addCallback(lambda x : t.stopService)
        d.addCallback(lambda x : self.assertEqual(
            [ZeroDivisionError],
            [o.value.__class__ for o in self.flushLoggedErrors(ZeroDivisionError)]))
        return d 
Example #14
Source File: test_application.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testTimerRuns(self):
        d = defer.Deferred()
        self.t = internet.TimerService(1, d.callback, 'hello')
        self.t.startService()
        d.addCallback(self.assertEqual, 'hello')
        d.addCallback(lambda x : self.t.stopService())
        d.addCallback(lambda x : self.failIf(self.t.running))
        return d 
Example #15
Source File: test_stats.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_a_TimerService(self):
        service = stats.PrometheusService()
        self.assertIsInstance(service, TimerService) 
Example #16
Source File: _twistw.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def postApplication(self):
        """
        Start the application and run the reactor.
        """
        service.IService(self.application).privilegedStartService()
        app.startApplication(self.application, not self.config['no_save'])
        app.startApplication(internet.TimerService(0.1, lambda:None), 0)
        self.startReactor(None, self.oldstdout, self.oldstderr)
        log.msg("Server Shut Down.") 
Example #17
Source File: relaymanager.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def RelayStateHelper(manager, delay):
    return internet.TimerService(delay, _checkState, manager) 
Example #18
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testPickledTimer(self):
        target = TimerTarget()
        t0 = internet.TimerService(1, target.append, "hello")
        t0.startService()
        s = pickle.dumps(t0)
        t0.stopService()

        t = pickle.loads(s)
        self.failIf(t.running) 
Example #19
Source File: test_bootresources.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_a_TimerService(self):
        service = bootresources.ImportResourcesProgressService()
        self.assertIsInstance(service, TimerService) 
Example #20
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testTimerRuns(self):
        d = defer.Deferred()
        self.t = internet.TimerService(1, d.callback, 'hello')
        self.t.startService()
        d.addCallback(self.assertEqual, 'hello')
        d.addCallback(lambda x : self.t.stopService())
        d.addCallback(lambda x : self.failIf(self.t.running))
        return d 
Example #21
Source File: active_discovery.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def run(self):
        """Called when the TimerService fires indicating it's time to scan.

        Also called by the postgresListener if the configuration changes.

        This function must be careful to trap any errors in any Deferred
        objects it returns, since they will run in the TimerService's
        LoopingCall, and the TimerService will stop running if the call's
        errback is invoked.

        :return: Deferred (or None if no action is necessary)
        """
        # This method needs to be as simple as possible so that it always adds
        # an errback to the Deferred it returns. (Otherwise, the TimerService
        # will silently stop.)
        if self.discovery_enabled is None:
            # The first time the service runs, the last_seen time will not be
            # initialized. So first gather the settings from the database.
            # Subsequent runs do not need to hit the database, since the
            # postgresListener will inform us if the interval or last_scan time
            # changes. (And those values will be double-checked after taking
            # the lock if we decide it's time to scan.)
            d = maybeDeferred(self.refreshDiscoveryConfig)
            d.addErrback(self.refreshFailed)
            return d
        elif self.discovery_enabled:
            d = maybeDeferred(self.scanIfNeeded)
            d.addErrback(self.activeScanFailed)
            return d
        else:
            return None 
Example #22
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testTimerRuns(self):
        d = defer.Deferred()
        self.t = internet.TimerService(1, d.callback, 'hello')
        self.t.startService()
        d.addCallback(self.assertEqual, 'hello')
        d.addCallback(lambda x : self.t.stopService())
        d.addCallback(lambda x : self.assertFalse(self.t.running))
        return d 
Example #23
Source File: bootresources.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _import_resources_in_thread(notify=None):
    """Import boot resources in a thread managed by Twisted.

    Errors are logged. The returned `Deferred` will never errback so it's safe
    to use in a `TimerService`, for example.

    :param notify: Instance of `Deferred` that is called when all the metadata
        has been downloaded and the image data download has been started.
    """
    d = deferToDatabase(_import_resources, notify=notify)
    d.addErrback(_handle_import_failures)
    return d 
Example #24
Source File: kdht.py    From simDHT with MIT License 5 votes vote down vote up
def timer(step, callback, *args):
    """定时器"""
    s = internet.TimerService(step, callback, *args)
    s.startService()
    return s 
Example #25
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_inert_client_service():
    service = ClusterClientService(Clock())
    # ClusterClientService's superclass, TimerService, creates a
    # LoopingCall with now=True. We neuter it here to allow
    # observation of the behaviour of _update_interval() for
    # example.
    service.call = (lambda: None, (), {})
    return service 
Example #26
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_init_sets_appropriate_instance_attributes(self):
        service = ClusterClientService(sentinel.reactor)
        self.assertThat(service, IsInstance(TimerService))
        self.assertThat(service.clock, Is(sentinel.reactor)) 
Example #27
Source File: services.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(
        self, clock=None, enable_monitoring=True, enable_beaconing=True
    ):
        # Order is very important here. First we set the clock to the passed-in
        # reactor, so that unit tests can fake out the clock if necessary.
        # Then we call super(). The superclass will set up the structures
        # required to add parents to this service, which allows the remainder
        # of this method to succeed. (And do so without the side-effect of
        # executing calls that shouldn't be executed based on the desired
        # reactor.)
        self.clock = clock
        super().__init__()
        self.enable_monitoring = enable_monitoring
        self.enable_beaconing = enable_beaconing
        # The last successfully recorded interfaces.
        self._recorded = None
        self._monitored = frozenset()
        self._beaconing = frozenset()
        self._monitoring_state = {}
        self._monitoring_mdns = False
        self._locked = False
        # Use a named filesystem lock to prevent more than one monitoring
        # service running on each host machine. This service attempts to
        # acquire this lock on each loop, and then it holds the lock until the
        # service stops.
        self._lock = NetworksMonitoringLock()
        # Set up child service to update interface.
        self.interface_monitor = TimerService(
            self.interval, self.updateInterfaces
        )
        self.interface_monitor.setName("updateInterfaces")
        self.interface_monitor.clock = self.clock
        self.interface_monitor.setServiceParent(self)
        self.beaconing_protocol = None 
Example #28
Source File: test_stats.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_a_TimerService(self):
        service = stats.StatsService()
        self.assertIsInstance(service, TimerService) 
Example #29
Source File: test_image_download_service.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_init(self):
        service = ImageDownloadService(
            sentinel.service, sentinel.tftp_root, sentinel.clock
        )
        self.assertIsInstance(service, TimerService)
        self.assertIs(service.clock, sentinel.clock)
        self.assertIs(service.client_service, sentinel.service)
        self.assertIs(service.tftp_root, sentinel.tftp_root) 
Example #30
Source File: _clusterstate.py    From flocker with Apache License 2.0 5 votes vote down vote up
def __init__(self, reactor):
        MultiService.__init__(self)
        self._deployment_state = DeploymentState()
        timer = TimerService(1, self._wipe_expired)
        timer.clock = reactor
        timer.setServiceParent(self)
        self._information_wipers = pmap()
        self._clock = reactor