当前位置: 首页>>代码示例>>Python>>正文


Python Timer.daemon方法代码示例

本文整理汇总了Python中threading.Timer.daemon方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.daemon方法的具体用法?Python Timer.daemon怎么用?Python Timer.daemon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Timer的用法示例。


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

示例1: open_connections

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def open_connections(self, host, user, password, db, poolsize=None):
        # pt: persist timer
        global conns
        global cursors
        global ps_socket


        curs = []

        self.db = db
        # Default connection pool = 10
        if not poolsize:
            poolsize = 10
            
        for _ in range(poolsize):
            con = mdb.connect(host, user, password, db)
            conns.append(con);
            curs.append(con.cursor(mdb.cursors.DictCursor))
        cursors = itertools.cycle(curs)
        dtd = Timer(5.0, self.__dump_to_database__,[self.persist_timer])
        dtd.daemon = True
        dtd.start()
        
        ka = Timer(18000.0, self.keepalive)
        ka.daemon = True
        ka.start()
开发者ID:Mondego,项目名称:rcat,代码行数:28,代码来源:mysqlconn.py

示例2: execute

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def execute(self):
        """
        Queue all Jobs for execution
        """
        status, created = models.Cron.objects.get_or_create(pk=1)

        # This is important for 2 reasons:
        #     1. It keeps us for running more than one instance of the
        #        same job at a time
        #     2. It reduces the number of polling threads because they
        #        get killed off if they happen to check while another
        #        one is already executing a job (only occurs with
        #		 multi-threaded servers)
        if status.executing:
            return

        status.executing = True
        try:
            status.save()
        except:
            # this will fail if you're debugging, so we want it
            # to fail silently and start the timer again so we
            # can pick up where we left off once debugging is done
            thread = Timer(polling_frequency, self.execute)
            thread.daemon = True
            thread.start()
            return

        jobs = models.Job.objects.all()
        for job in jobs:
            if job.queued:
                time_delta = timezone.now() - job.last_run
                if (time_delta.seconds + 86400 * time_delta.days) > job.run_frequency:
                    inst = cPickle.loads(str(job.instance))
                    args = cPickle.loads(str(job.args))
                    kwargs = cPickle.loads(str(job.kwargs))

                    try:
                        inst.run(*args, **kwargs)
                        job.last_run = timezone.now()
                        job.save()

                    except Exception:
                        # if the job throws an error, just remove it from
                        # the queue. That way we can find/fix the error and
                        # requeue the job manually
                        job.queued = False
                        job.save()

        status.executing = False
        status.save()

        # Set up for this function to run again
        thread = Timer(polling_frequency, self.execute)
        thread.daemon = True
        thread.start()
开发者ID:mbschenkel,项目名称:bioco-intranet,代码行数:58,代码来源:base.py

示例3: check_time_server

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
 def check_time_server(self):
     """Sets Timers to repeatedly set offsets (if leader) or check time server."""
     ack = self.check_server_activity()
     if self.am_leader:
         t = Timer(5, self.set_offset_for_processes)
         t.daemon = True
         t.start()
     else:
         t = Timer(10, self.check_time_server)
         t.daemon = True
         t.start()
     return ack
开发者ID:jwnewman,项目名称:asterix,代码行数:14,代码来源:AsyncXMLRPCServer.py

示例4: idle

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def idle(self, bounce_timer = (29 * 60) ):
        '''
        Use this method to initiate IDLE mode.

        bounce_timer: The IDLE spec suggests stopping and restarting IDLE
            every 29 minutes in order to avoid timing out. This is the default,
            and there should be no need to change it. If you find that your 
            connection is timing out anyway however change this value to something
            lower.

        Note that this method is blocking and should be run in a thread.
        '''
        name = 'IDLE'

        if name not in self.capabilities:
            raise self.Abort('Server does not support IDLE')
        tag = self._new_tag()
        data = '%s %s' % (tag, name)
        self.send('%s%s' % (data, CRLF))

        response = self._get_line()
        if 'accepted, awaiting DONE command' in response or 'idling' in response:
            self.state = name
            tmr = Timer(bounce_timer, self._bounce_idle)
            tmr.daemon = True
            tmr.start()
            final_response = self._coreader(tag)
            tmr.cancel()
            return final_response
        else:
            self.Abort('Failed to initiate IDLE! Got error %s' % response)
开发者ID:dlobue,项目名称:idle_imapmonkey,代码行数:33,代码来源:monkey_magic.py

示例5: scan_for_contests

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def scan_for_contests():
        time = get_fuzzed_time(s['search']['base'], s['search']['fuzz'])
        minutes, seconds = divmod(time, 60)
        hours, minutes = divmod(minutes, 60)
        out("scan_for_contests random time: %sh%sm%ss" % (
            int(hours), int(minutes), int(seconds)
        ))

        # Setup and start the threading
        v = Timer(time, scan_for_contests)
        v.daemon = True
        v.start()

        mutex.acquire()
        try:
            out("Scanning For Contests...")
            last_twitter_id = p.get_last_twitter_id()

            try:
                #"RT to win" music OR sound OR speaker OR dj OR mixer OR gear'
                results = t.api.GetSearch(
                    term='"RT to win"',
                    since_id=last_twitter_id
                )

                for status in results:
                    item = status.AsDict()
                    if 'retweet_count' in item and item['retweet_count'] > 0:
                        if item['id'] > last_twitter_id:
                            p.set_last_twitter_id(item['id'])
                            contests.append(item)
            except Exception as e:
                err("[scan_for_contests] Search Error: %s" % e)
        finally:
            mutex.release()
开发者ID:DJSymBiotiX,项目名称:ochobot,代码行数:37,代码来源:winner.py

示例6: update_queue

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def update_queue():
        time = get_fuzzed_time(s['retweet']['base'], s['retweet']['fuzz'])
        minutes, seconds = divmod(time, 60)
        hours, minutes = divmod(minutes, 60)
        out("update_queue random time: %sh%sm%ss" % (
            int(hours), int(minutes), int(seconds)
        ))

        # Setup and start the threading
        u = Timer(time, update_queue)
        u.daemon = True
        u.start()

        mutex.acquire()
        try:
            if len(contests) > 0:
                contest = contests[0]
                out("Contest: %s" % contest['text'])

                followed = check_for_follow_request(contest, t, p, s)
                favourited = check_for_favourite_request(contest, t, p, s)
                retweet_post(contest, t, p, s, followed, favourited)

                contests.pop(0)
        finally:
            mutex.release()
开发者ID:DJSymBiotiX,项目名称:ochobot,代码行数:28,代码来源:winner.py

示例7: _update_time

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
 def _update_time(self):
     """Update the Aquaero real time clock and then wait for the next turn."""
     self.device.set_time()
     if not self.shutdown:
         timer = Timer(self.frequency, lambda: self._update_time())
         timer.daemon = True
         timer.start()
开发者ID:shred,项目名称:pyquaero,代码行数:9,代码来源:server.py

示例8: _check_streams

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def _check_streams(self):
        if not self.stream_names:
            return

        global _timer
        output = []
        try:
            data = self.retrieve_stream_data(self.stream_names)
        except:
            data = dict()
        for stream, params in data.iteritems():
            if not params:
                self.cache.set(stream, STATUS_OFFLINE)
                continue
            try:
                previous_state = int(self.cache.get(stream))
            except (TypeError, ValueError):
                previous_state = None
            if previous_state in (None, STATUS_OFFLINE):
                output.append(MESSAGE_TEMPLATE.format(**params))
            self.cache.set(stream, STATUS_ONLINE)

        if self.whitelist and output:
            message = "\n".join(output)
            responses = dispatcher.send(signals.REQUEST_CHATS)
            chats = responses[0]
            for chat in chats:
                if chat_is_whitelisted(chat, self.whitelist):
                    self.output.append(ChatMessage(chat, message))

        _timer = Timer(self.check_interval, self._check_streams)
        _timer.daemon = True
        _timer.start()
开发者ID:tetra5,项目名称:gooby,代码行数:35,代码来源:twitchtvnotifier.py

示例9: run

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
 def run(self):
     with app.app_context():
         print("running task {time}".format(time=datetime.datetime.now().time().isoformat()))
         self.callback(**self.kwargs)
         t = Timer(self.interval, self.run)
         t.daemon = self.daemon
         t.start()
开发者ID:ajholyoake,项目名称:spot_tracker,代码行数:9,代码来源:app.py

示例10: play

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
def play(args):
    """Handles the 'play' command."""
    from threading import Timer
    from lib.configuration import Configuration
    from lib.task import Task

    config = utils.parse_config(args, Configuration())

    tasks = []
    for task, items in config.tasks.items():
        t = Timer(items['timing'], Task.run_task,
                args=(task, len(tasks) + 1, items, config))
        t.daemon = True
        t.start()
        tasks.append(t)

    duration = config.duration
    if duration == 0:
        for t in tasks:
            t.join()
    else:
        start = time.time()
        while time.time() < start + duration:
            finished = True
            for t in tasks:
                if not t.finished.is_set():
                    finished = False
                    break
            if finished:
                break
            time.sleep(1)
开发者ID:akheros,项目名称:moirai,代码行数:33,代码来源:parser.py

示例11: run_defence_planner

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
 def run_defence_planner():
     global defence_timer
     delay = defence_planner.plan_and_act(latest_world)
     defence_timer.cancel()
     defence_timer = Timer(delay, run_defence_planner)
     defence_timer.daemon = True
     defence_timer.start()
开发者ID:modulo-,项目名称:SDP-2016-Team-F,代码行数:9,代码来源:main.py

示例12: scheduleFlight

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
def scheduleFlight(res, flight, blocking=False, scheduler=None):
  flight_time = time_module.mktime(flight.legs[0].depart.dt_utc.utctimetuple()) - time_module.timezone
  seconds_before = config["CHECKIN_WINDOW"] + 24*60*60 # how many seconds before the flight time do we check in
  flight.sched_time = flight_time - seconds_before
  flight.sched_time_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc) - timedelta(seconds=seconds_before))
  flight.seconds = flight.sched_time - time_module.time()
  # Retrieve timezone and apply it because datetimes are stored as naive (no timezone information)
  tz = airport_timezone_map[flight.legs[0].depart.airport]
  flight.sched_time_local_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc).astimezone(tz) - timedelta(seconds=seconds_before))
  db.Session.commit()
  dlog("Flight time: %s" % flight.legs[0].depart.dt_formatted)
  if config["CELERY"]:
    from tasks import check_in_flight
    result = check_in_flight.apply_async([res.id, flight.id], countdown=flight.seconds)
    flight.task_uuid = result.id
    db.Session.commit()
  elif not blocking:
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC) in", int(flight.seconds/60/60), "hrs", int(flight.seconds/60%60),  "mins from now..."
    t = Timer(flight.seconds, TryCheckinFlight, (res.id, flight.id, None, 1))
    t.daemon = True
    t.start()
    # DEBUG
    # if flight == res.flights[0]:
    #   Timer(5, TryCheckinFlight, (res, flight, None, 1)).start()
  else:
    scheduler.enterabs(flight.sched_time, 1, TryCheckinFlight, (res.id, flight.id, scheduler, 1))
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC)"
  print result
  dlog('Checkin scheduled at (UTC): %s' % flight.sched_time_formatted)
  dlog('Checkin scheduled at (local): %s' % flight.sched_time_local_formatted)
  dlog('Flights scheduled.  Waiting...')
  return result
开发者ID:alexbstl,项目名称:southwest-checkin,代码行数:34,代码来源:sw_checkin_email.py

示例13: broadcast_dis

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def broadcast_dis(self):
        """Broadcast a DIS message on all interfaces
        1.build_dis
        2. broadcast_backet (dis)
        Called by: rpl_node on init
        """
        logger.debug("checking if a DIS broadcast is required")
        if self.dodag_cache.is_empty():
            logger.debug("broadcasting DIS")
            # Create RPL_DIO message
            dismsg = icmpv6_rpl.rpl_dis()
            
            # Create Dodag RPL Control message        
            rplmsg = icmpv6_rpl.rpl_control(code=icmpv6_rpl.RPL_DIO, rplctrl=dismsg)
        
            # Create ICMPv6 protocol message        
            rpl = icmpv6.icmpv6(type_= icmpv6_rpl.ICMPv6_RPL, code=icmpv6_rpl.RPL_DIS,
                          csum=0, data= rplmsg)

            self._broadcast_rpl_pkt(rpl)
        else:
            logger.debug("no DIS is required")
        dis_timer = Timer(DEFAULT_INTERVAL_BETWEEN_DIS, broadcast_dis, kwargs= {})
        dis_timer.daemon = True
        dis_timer.start()
开发者ID:abdelwas,项目名称:Ryu-RPL,代码行数:27,代码来源:rpl_node.py

示例14: reset_timer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
def reset_timer(sprout, pool, timeout):
    global timer
    if timer:
        timer.cancel()
    timer = Timer((timeout / 2) * 60, lambda: ping_pool(sprout, pool, timeout))
    timer.daemon = True
    timer.start()
开发者ID:MattLombana,项目名称:cfme_tests,代码行数:9,代码来源:single_appliance_sprout.py

示例15: _poll_skill_settings

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import daemon [as 别名]
    def _poll_skill_settings(self):
        """ If identifier exists for this skill poll to backend to
            request settings and store it if it changes
            TODO: implement as websocket

            Args:
                hashed_meta (int): the hashed identifier
        """
        try:
            if not self._complete_intialization:
                self.initialize_remote_settings()
                if not self._complete_intialization:
                    return  # unable to do remote sync
            else:
                original = hash(str(self))
                self.update_remote()
                # Call callback for updated settings
                if self.changed_callback and hash(str(self)) != original:
                    self.changed_callback()

        except Exception as e:
            LOG.error(e)
            LOG.exception("")

        # this is used in core so do not delete!
        if self.is_alive:
            # continues to poll settings every 60 seconds
            t = Timer(60, self._poll_skill_settings)
            t.daemon = True
            t.start()
开发者ID:Ceda-EI,项目名称:mycroft-core,代码行数:32,代码来源:settings.py


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