• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python reactor.addSystemEventTrigger函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.internet.reactor.addSystemEventTrigger函数的典型用法代码示例。如果您正苦于以下问题:Python addSystemEventTrigger函数的具体用法?Python addSystemEventTrigger怎么用?Python addSystemEventTrigger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了addSystemEventTrigger函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, options):
        """
        @param options: the optparsed dictionary of command-line options
        @type  options: an object with attributes
        """
        self.options = options
        self.workerName = options.name

        # the last port is reserved for our FeedServer
        if not self.options.randomFeederports:
            self.ports = self.options.feederports[:-1]
        else:
            self.ports = []

        self.medium = medium.WorkerMedium(self)

        # really should be componentJobHeaven, but this is shorter :)
        self.jobHeaven = job.ComponentJobHeaven(self)
        # for ephemeral checks
        self.checkHeaven = job.CheckJobHeaven(self)

        self.managerConnectionInfo = None

        # it's possible we don't have a feed server, if we are
        # configured to have 0 tcp ports; setup this in listen()
        self.feedServer = None

        self.stopping = False
        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdownHandler)
        self._installHUPHandler()
开发者ID:ApsOps,项目名称:flumotion-orig,代码行数:31,代码来源:worker.py


示例2: wsgi_resource

def wsgi_resource():
    pool = threadpool.ThreadPool()
    pool.start()
    # Allow Ctrl-C to get you out cleanly:
    reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
    wsgi_resource = wsgi.WSGIResource(reactor, pool, get_internal_wsgi_application())
    return wsgi_resource
开发者ID:gilligan,项目名称:bebop,代码行数:7,代码来源:runbebop.py


示例3: applicationShouldTerminate_

 def applicationShouldTerminate_(self, sender):
     if reactor.running:
         reactor.addSystemEventTrigger(
             'after', 'shutdown', AppHelper.stopEventLoop)
         reactor.stop()
         return False
     return True
开发者ID:BMXE,项目名称:music-player,代码行数:7,代码来源:WSTApplicationDelegateClass.py


示例4: GetworkProxy_main

def GetworkProxy_main(cb):
    log.info("Stratum proxy version %s Connecting to Pool..." % version.VERSION)
        
    # Connect to Stratum pool
    f = SocketTransportClientFactory(settings.HOSTNAME, settings.LISTEN_SOCKET_TRANSPORT,
                debug=False, proxy=None, event_handler=client_service.ClientMiningService)
    
    job_registry = jobs.JobRegistry(f, cmd='', no_midstate=settings.GW_DISABLE_MIDSTATE, real_target=settings.GW_SEND_REAL_TARGET)
    client_service.ClientMiningService.job_registry = job_registry
    client_service.ClientMiningService.reset_timeout()
    
    workers = worker_registry.WorkerRegistry(f)
    f.on_connect.addCallback(on_connect, workers, job_registry)
    f.on_disconnect.addCallback(on_disconnect, workers, job_registry)
    
    # Cleanup properly on shutdown
    reactor.addSystemEventTrigger('before', 'shutdown', on_shutdown, f)

    # Block until proxy connects to the pool
    yield f.on_connect
    
    # Setup getwork listener
    gw_site = Site(getwork_listener.Root(job_registry, workers,
		stratum_host=settings.HOSTNAME, stratum_port=settings.LISTEN_SOCKET_TRANSPORT,
		custom_lp=False, custom_stratum=False,
		custom_user=False, custom_password=False
		))
    gw_site.noisy = False
    reactor.listenTCP(settings.GW_PORT, gw_site, interface='0.0.0.0')
    
    log.info("Getwork Proxy is online, Port: %d" % (settings.GW_PORT))
开发者ID:feeleep75,项目名称:stratum-mining-litecoin,代码行数:31,代码来源:getwork_proxy.py


示例5: launch_stdout_downloader

def launch_stdout_downloader():

    from twisted.internet import reactor

    logging.basicConfig(level=logging.WARNING, filename="dl.log")
    if len(sys.argv) == 3:
        downloader = StdoutDownloader(int(sys.argv[2]), [])
    elif len(sys.argv) == 5:
        downloader = StdoutDownloader(int(sys.argv[2]), [(sys.argv[3], int(sys.argv[4]))])
    else:
        print "Usage: lbrynet-stdout-downloader <sd_hash> <peer_port> <dht_node_port>" \
              " [<dht_bootstrap_host> <dht_bootstrap port>]"
        sys.exit(1)

    def start_stdout_downloader():
        return downloader.start_download(sys.argv[1])

    def print_error(err):
        logging.warning(err.getErrorMessage())

    def shut_down():
        reactor.stop()

    d = task.deferLater(reactor, 0, downloader.start)
    d.addCallback(lambda _: start_stdout_downloader())
    d.addErrback(print_error)
    d.addCallback(lambda _: shut_down())
    reactor.addSystemEventTrigger('before', 'shutdown', downloader.shut_down)
    reactor.run()
开发者ID:Fillerix99,项目名称:lbry,代码行数:29,代码来源:StdoutDownloader.py


示例6: connect_tunnel

def connect_tunnel(tunnel_id,
                 base_url,
                 username,
                 access_key,
                 local_host,
                 remote_host,
                 ports,
                 connected_callback,
                 shutdown_callback,
                 diagnostic):

    def check_n_call():
        global open_tunnels
        open_tunnels += 1
        if open_tunnels >= len(ports) and connected_callback:
            connected_callback()

    for (local_port, remote_port) in ports:
        d = protocol.ClientCreator(reactor,
                                   TunnelTransport,
                                   username,
                                   access_key,
                                   local_host,
                                   local_port,
                                   remote_port,
                                   check_n_call,
                                   diagnostic).connectTCP(remote_host, 22)

    reactor.addSystemEventTrigger("before", "shutdown", shutdown_callback)
开发者ID:santiycr,项目名称:saucerest-python,代码行数:29,代码来源:sshtunnel.py


示例7: __init__

    def __init__(self, endpoint, maxClients=5, reactor=None):
        """
        @param endpoint: An L{IStreamClientEndpoint} indicating the server to
            connect to.

        @param maxClients: A C{int} indicating the maximum number of clients.

        @param reactor: An L{IReactorTCP} provider used to initiate new
            connections.
        """
        self._endpoint = endpoint
        self._maxClients = maxClients

        if reactor is None:
            from twisted.internet import reactor
        self._reactor = reactor

        self.shutdown_deferred = None
        self.shutdown_requested = False
        reactor.addSystemEventTrigger(
            'before', 'shutdown', self._shutdownCallback
        )

        self._busyClients = set([])
        self._freeClients = set([])
        self._pendingConnects = 0
        self._commands = []
开发者ID:eventable,项目名称:CalendarServer,代码行数:27,代码来源:memcachepool.py


示例8: configure

def configure(protocol, port, pipes, interface):
  remove_all()
  reactor.addSystemEventTrigger('after', 'shutdown', remove_all)

  # gets default (outward-facing) network interface (e.g. deciding which of
  # eth0, eth1, wlan0 is being used by the system to connect to the internet)
  if interface == "auto":
    interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
  else:
    if interface not in netifaces.interfaces():
      raise ValueError("Given interface does not exist.", interface)

  add(protocol, port, interface)
  manager = libnetfilter_queue.Manager()

  def on_up(packet):
    def accept():
      manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
    pipes.up.attempt(accept, packet.size)

  def on_down(packet):
    def accept():
      manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
    pipes.down.attempt(accept, packet.size)

  manager.bind(UP_QUEUE, on_up)
  manager.bind(DOWN_QUEUE, on_down)

  reader = abstract.FileDescriptor()
  reader.doRead = manager.process
  reader.fileno = lambda: manager.fileno
  reactor.addReader(reader)
开发者ID:kleopatra999,项目名称:packet-queue,代码行数:32,代码来源:nfqueue.py


示例9: main

    def main(self):
        """
        Start the main event loop.
        """
        if self.options.cycle:
            reactor.callLater(0, self.heartbeat)
            self.log.debug("Creating async MetricReporter")
            self._metric_manager.start()
            reactor.addSystemEventTrigger(
                'before', 'shutdown', self._metric_manager.stop
            )
            # preserve legacy API
            self.metricreporter = self._metric_manager.metricreporter

        # Start ZenHub services
        self._service_manager.start(self.dmd, reactor)
        self._service_manager.onExecute(self.__workerItemCounter)

        # Start Processing Invalidations
        self.process_invalidations_task = task.LoopingCall(
            self._invalidation_manager.process_invalidations
        )
        self.process_invalidations_task.start(
            self.options.invalidation_poll_interval
        )

        reactor.run()

        self.shutdown = True
        getUtility(IEventPublisher).close()
        if self.options.profiling:
            self.profiler.stop()
开发者ID:zenoss,项目名称:zenoss-prodbin,代码行数:32,代码来源:zenhub.py


示例10: start

def start():
   # Import the module containing the resources
    import sse

    pool = threadpool.ThreadPool()
    pool.start()

    # Prepare the app root and subscribe endpoint
    root        = sse.Root()
    subscribe   = sse.Subscribe()
    broadcast   = sse.Broadcast(subscribe.publish_to_all)
    connections = sse.Connections(subscribe.get_subscribers_count)

    # Add sse and connections as children of root
    root.putChild('sse', subscribe)
    root.putChild('connections', connections)
    root.putChild('broadcast', broadcast)

    # Allow Ctrl-C to get you out cleanly:
    reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)

    # emit an event every second
    l = task.LoopingCall(publish_timestamp, { "broadcast": subscribe.publish_to_all })
    l.start(1.0)

    site = twisted_server.Site(root)
    server = internet.TCPServer(1942, site)
    application = service.Application("twisted-sse")
    server.setServiceParent(application)
    return application
开发者ID:einaros,项目名称:sse-broadcast-benchmark,代码行数:30,代码来源:server.py


示例11: stop

 def stop(self):
     # stop the reactor
     key = self.getKey()
     reactor.addSystemEventTrigger('after', 'shutdown',
         self._stopIterating, True, key)
     reactor.stop()
     self.iterate(key)
开发者ID:BillAndersan,项目名称:twisted,代码行数:7,代码来源:blockingdemo.py


示例12: __init__

 def __init__(self, interface='', status_port=0, device_target=''):
     self.interface = interface
     self.device_target = device_target
     self.status_port = status_port
     self.port = reactor.listenMulticast(SSDP_PORT, self, listenMultiple=True) # pylint: disable=no-member
     self.port.joinGroup(SSDP_ADDR, interface=interface)
     reactor.addSystemEventTrigger('before', 'shutdown', self.stop) # pylint: disable=no-member
开发者ID:asishv,项目名称:smartthingsv2,代码行数:7,代码来源:rpi_contact_sensor.py


示例13: shutdown

def shutdown(killPostProcessors = False, message = None):
    """ Turn the knob that tells all parts of the program we're shutting down, optionally kill
    any sub processes (that could prevent the program from exiting) and kill the twisted
    reactor """
    if Hellanzb.SHUTDOWN:
        # shutdown already triggered
        return
    
    # that knob, that threads (PostProcessors) will check on before doing significant work
    Hellanzb.SHUTDOWN = True

    if killPostProcessors:
        # However PostProcessors may be running sub-processes, which are all kill -9ed
        # here
        Topen.killAll()

    if not getattr(Hellanzb, 'shutdownMessage', None):
        Hellanzb.shutdownMessage = message
    
    # stop the twisted reactor
    if reactor.running:
        # hellanzb downloader processes will call finishShutdown after reactor.run has
        # completed (it has to: because the system event trigger below does NOT ensure
        # finishShutdown is called in the final reactor iteration)
        if not Hellanzb.IS_DOWNLOADER:
            reactor.addSystemEventTrigger('after', 'shutdown', finishShutdown)
        reactor.stop()
    else:
        finishShutdown()
开发者ID:Bootz,项目名称:hellanzb,代码行数:29,代码来源:Core.py


示例14: __init__

    def __init__(self, fd=42):
        self.pid = os.getpid()

        with os.fdopen(fd, 'r') as f:
            self.cfg = json.loads(f.read())

        self._log = os.fdopen(0, 'w', 1).write

        set_proc_title(self.name)
        set_pdeathsig(signal.SIGTERM)

        def _sigusr1(SIG, FRM):
            self.sigusr1()

        signal.signal(signal.SIGUSR1, _sigusr1)

        def _sigusr2(SIG, FRM):
            self.sigusr2()

        signal.signal(signal.SIGUSR2, _sigusr2)

        def excepthook(*exc_info):
            self.log("".join(traceback.format_exception(*exc_info)))

        sys.excepthook = excepthook

        reactor.addSystemEventTrigger("before", "shutdown", self.shutdown)
开发者ID:chojar,项目名称:GlobaLeaks,代码行数:27,代码来源:process.py


示例15: __init__

    def __init__(self, application):
        """
        Setup the server.

        Args:
            application (Application): An instantiated Twisted application

        """
        sys.path.append('.')

        # create a store of services
        self.services = service.IServiceCollection(application)
        self.amp_protocol = None  # set by amp factory
        self.sessions = PORTAL_SESSIONS
        self.sessions.portal = self
        self.process_id = os.getpid()

        self.server_process_id = None
        self.server_restart_mode = "shutdown"
        self.server_info_dict = {}

        # in non-interactive portal mode, this gets overwritten by
        # cmdline sent by the evennia launcher
        self.server_twistd_cmd = self._get_backup_server_twistd_cmd()

        # set a callback if the server is killed abruptly,
        # by Ctrl-C, reboot etc.
        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown, _reactor_stopping=True, _stop_server=True)
开发者ID:Henddher,项目名称:evennia,代码行数:29,代码来源:portal.py


示例16: __init__

    def __init__(self, application, port=80, resources=None, services=None, loud=False):
        service.MultiService.__init__(self)

        # Create, start and add a thread pool service, which is made available
        # to our WSGIResource within HendrixResource
        threads = ThreadPool()
        reactor.addSystemEventTrigger('after', 'shutdown', threads.stop)
        ThreadPoolService(threads).setServiceParent(self)

        # create the base resource and add any additional static resources
        resource = HendrixResource(reactor, threads, application, loud=loud)
        if resources:
            for res in resources:
                resource.putNamedChild(res)


        factory = server.Site(resource)
        # add a tcp server that binds to port=port
        main_web_tcp = TCPServer(port, factory)
        main_web_tcp.setName('main_web_tcp')  # to get this at runtime use hedrix_service.getServiceNamed('main_web_tcp')
        main_web_tcp.setServiceParent(self)

        # add any additional services
        if services:
            logger.info('loaded %r at %r'%(srv,srv_name))
            for srv_name, srv in services:
                srv.setName(srv_name)
                srv.setServiceParent(self)
开发者ID:damonworx,项目名称:hendrix,代码行数:28,代码来源:services.py


示例17: main

def main(args=None):
    """
    Starts the daemon.

    :param list args: List of the console parameters
    """
    if args is None:
        args = sys.argv[1:]

    pid = os.getpid()
    logging.basicConfig(filename=os.path.join(conf.LOGGING_DIR, 'polod.log'),
                        level=conf.LOGGING_LEVEL.upper(),
                        format=conf.LOGGING_FORMAT)

    #try:
    #    f = open(conf.PIDFILE_POLO, 'w')
    #    f.write(str(pid))
    #    f.close()
    #except Exception as e:
    #    logging.error(e)
    #    sys.exit(1)

    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    signal.signal(signal.SIGUSR1, reload_services)
    
    reactor.addSystemEventTrigger('before', 'shutdown', graceful_shutdown)
    reactor.callWhenRunning(start_multicast)
    reactor.callWhenRunning(start_binding)
    reactor.run()
开发者ID:Alternhuman,项目名称:marcopolo,代码行数:29,代码来源:polod.py


示例18: __init__

 def __init__(self, name, behavior='delete', ttl=None, heartbeat_interval=None, lock_delay=None, host=CONSUL_HOST,
              port=CONSUL_PORT, token=CONSUL_TOKEN, scheme=CONSUL_SCHEME, dc=CONSUL_DC, verify=CONSUL_VERIFY,
              **kwargs):
     """
     :type behavior: str
     :param behavior: consul session behavior (release, delete)
     :type ttl: int
     :param ttl: time to live for the session before it is invalidated
     :param name: session name to use
     :type name: str
     :param heartbeat_interval: interval (in seconds) in which a session
         should be renewed, this value is also used as the session ttl.
     :type heartbeat_interval: str
     :type lock_delay: int
     :param lock_delay: consul lock delay to use for sessions
     """
     assert behavior in ('release', 'delete')
     self.name = name
     self.ttl = ttl or self.SESSION_TTL_SECONDS
     self.heartbeat_interval = heartbeat_interval or self.SESSION_HEARTBEAT_SECONDS
     self.lock_delay = lock_delay or self.SESSION_LOCK_DELAY_SECONDS
     if 0 > self.lock_delay > 60:
         self.logger.debug('invalid lock-delay=%s specified, using defaults', self.lock_delay)
         self.lock_delay = 15
     self.consul = Consul(host=host, port=port, token=token, scheme=scheme, dc=dc, verify=verify, **kwargs)
     self.session = None
     self.heartbeat = task.LoopingCall(self.session_renew)
     reactor.callLater(0, self.session_create)
     self.start()
     reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
     reactor.addSystemEventTrigger('before', 'shutdown', self.session_destroy)
开发者ID:joshainglis,项目名称:python-cafe-consul,代码行数:31,代码来源:agent.py


示例19: start_app_start

    def start_app_start(self):
        """Start the app for the start subcommand."""
        config = self.master_config
        # First see if the cluster is already running
        try:
            pid = self.get_pid_from_file()
        except PIDFileError:
            pass
        else:
            self.log.critical(
                'Cluster is already running with [pid=%s]. '
                'use "ipcluster stop" to stop the cluster.' % pid
            )
            # Here I exit with a unusual exit status that other processes
            # can watch for to learn how I existed.
            self.exit(ALREADY_STARTED)

        # Now log and daemonize
        self.log.info(
            'Starting ipcluster with [daemon=%r]' % config.Global.daemonize
        )
        # TODO: Get daemonize working on Windows or as a Windows Server.
        if config.Global.daemonize:
            if os.name=='posix':
                daemonize()

        # Now write the new pid file AFTER our new forked pid is active.
        self.write_pid_file()
        reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file)
        reactor.run()
开发者ID:08saikiranreddy,项目名称:ipython,代码行数:30,代码来源:ipclusterapp.py


示例20: __init__

 def __init__(self, config):
     self.config = config
     self.step = self.config[self.name]['step']
     self.call = (self.update_feed_list, [], {})
     self.pool = threadpool.ThreadPool(name=self.name)
     reactor.callWhenRunning(self.pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', self.pool.stop)
开发者ID:cato-,项目名称:django-feedjack,代码行数:7,代码来源:updater.py



注:本文中的twisted.internet.reactor.addSystemEventTrigger函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reactor.callFromThread函数代码示例发布时间:2022-05-27
下一篇:
Python reactor.addReader函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap