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


Python Timer.setName方法代码示例

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


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

示例1: program_next_poll

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
 def program_next_poll(self, interval, method, args, kwargs):
     t = Timer(interval=interval, function=self.poller,
               kwargs={'interval': interval, 'method': method, 'args': args, 'kwargs': kwargs})
     self.current_timers.append(t)  # save the timer to be able to kill it
     t.setName('Poller thread for %s' % type(method.__self__).__name__)
     t.setDaemon(True)  # so it is not locking on exit
     t.start()
开发者ID:gsass,项目名称:err,代码行数:9,代码来源:botplugin.py

示例2: scheduleOneTask

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
    def scheduleOneTask(self, task, immediate=False):
        if immediate:
            waitTime = 0
        else:
            waitTime = self.tactic(task) + 1
        t = time.gmtime()
        curtime = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], tzinfo=timezone.GMT())
        dt = curtime + datetime.timedelta(seconds=waitTime)

        dateFormat = dt.astimezone(timezone.getTimeZone(globalProperty.getTimeZone())).strftime(
            "%Y-%m-%d %H:%M:%S %A (%Z)"
        )

        # content = globalProperty.getRestSchTkMgrInstance().getContentOfJob(task['fileName'])
        self._dbutil.addNewScheduleJob(task, self.type, dateFormat)
        self.logger.info("Task %s will be kicked off on %s" % (str(task["fileName"]), dateFormat))

        fileName = task["fileName"]
        funcArgs = [str(fileName)]
        funcKwargs = task
        t = Timer(waitTime, self.popUpTaskHandle, funcArgs, funcKwargs)
        timerName = "timer_%s" % fileName
        t.setName(timerName)
        t.start()

        # Record timer
        self.__timerDic[fileName] = t
开发者ID:eveningwear,项目名称:aqua-release,代码行数:29,代码来源:TasksTypeMgr.py

示例3: SensorDataLogger

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
class SensorDataLogger(object):
    def __init__(self, sensors=[], interval=0.1, maxSamples=20000, name='Data logger'):
        self.sensors = sensors
        self.interval = interval  # period between samples in seconds
        self.name = name
        self.results = []
        self.maxSamples=maxSamples
        # self.basetime =time.time()
        self.is_running = False
    def getsample(self):
        # now = time.time()
        # Maybe have a FIFO queue to drop early samples and retain more recent ones?
        # Or something more intelligent? eg drop every othersample? (so resample, essentially?)
        if len(self.results) <= self.maxSamples:
            result=[datetime.now()]
            for s in self.sensors:
                result.append(s.value())
            self.results.append(result)
    def _run(self):
        self.is_running = False
        self.start()
        self.getsample()
    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.setName(self.name)
            self._timer.start()
            self.is_running = True
    def stop(self):
        self._timer.cancel()
        self.is_running = False
        #killThreads(self.name)
        # return self.results
    def log(self):
        return self.results
开发者ID:psychemedia,项目名称:ev3robotics,代码行数:37,代码来源:data_logger_stripes.py

示例4: program_next_poll

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
 def program_next_poll(self, interval, method, args, kwargs):
     t = Timer(
         interval=interval,
         function=self.poller,
         kwargs={"interval": interval, "method": method, "args": args, "kwargs": kwargs},
     )
     self.current_timers.append(t)  # save the timer to be able to kill it
     t.setName("Poller thread for %s" % type(method.__self__).__name__)
     t.setDaemon(True)  # so it is not locking on exit
     t.start()
开发者ID:armonge,项目名称:err,代码行数:12,代码来源:botplugin.py

示例5: setTimer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
 def setTimer(self, syncer):
     self.__lock.acquire()
     self.idle = False
     syncerName = syncer.getName() 
     timerName = "%s_timer" % syncerName
     funcArgs = [syncerName]
     funcKwargs = {}
     timer = Timer(self.timeout, self.__timesUp, funcArgs, funcKwargs)
     timer.setName(timerName)
     self.timerDic[timerName] = timer
     self.syncerDic[syncerName] = syncer
     timer.start()
     self.__lock.release()
开发者ID:eveningwear,项目名称:aqua-release,代码行数:15,代码来源:SynchronizerPool.py

示例6: notify

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
    def notify(self, subject, changeType, obj_id, *args):
        """
        Notify all interested observers about an event with threads from the pool
        """
        tasks = []
        assert subject in self.SUBJECTS, 'Subject %s not in SUBJECTS' % subject

        args = [subject, changeType, obj_id] + list(args)

        self.observerLock.acquire()
        for ofunc, osubject, ochangeTypes, oid, cache in self.observers:
            try:
                if (subject == osubject and
                    changeType in ochangeTypes and
                        (oid is None or oid == obj_id)):

                    if not cache:
                        tasks.append(ofunc)
                    else:
                        if ofunc not in self.observerscache:
                            def doQueue(ofunc):
                                self.observerLock.acquire()
                                if ofunc in self.observerscache:
                                    events = self.observerscache[ofunc]
                                    del self.observerscache[ofunc]
                                else:
                                    events = []
                                self.observerLock.release()

                                if events:
                                    if self.pool:
                                        self.pool.queueTask(ofunc, (events,))
                                    else:
                                        ofunc(events)

                            self.observerscache[ofunc] = []
                            t = Timer(cache, doQueue, (ofunc,))
                            t.setName("Notifier-timer")
                            t.start()

                        self.observerscache[ofunc].append(args)
            except:
                print_exc()
                print >> sys.stderr, "notify: OIDs were", repr(oid), repr(obj_id)

        self.observerLock.release()
        for task in tasks:
            if self.pool:
                self.pool.queueTask(task, args)
            else:
                task(*args)  # call observer function in this thread
开发者ID:Anbcorp,项目名称:tribler,代码行数:53,代码来源:Notifier.py

示例7: program_next_poll

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
    def program_next_poll(self,
                          interval: float,
                          method: Callable[..., None],
                          times: int=None,
                          args: Tuple=None,
                          kwargs: Mapping=None):
        if times is not None and times <= 0:
            return

        t = Timer(interval=interval, function=self.poller,
                  kwargs={'interval': interval, 'method': method,
                          'times': times, 'args': args, 'kwargs': kwargs})
        self.current_timers.append(t)  # save the timer to be able to kill it
        t.setName('Poller thread for %s' % type(method.__self__).__name__)
        t.setDaemon(True)  # so it is not locking on exit
        t.start()
开发者ID:apophys,项目名称:errbot,代码行数:18,代码来源:botplugin.py

示例8: NamedTimer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
def NamedTimer(*args,**kwargs):
    t = Timer(*args,**kwargs)
    t.setDaemon(True)
    t.setName("NamedTimer"+t.getName())
    return t
开发者ID:egbertbouman,项目名称:tribler-g,代码行数:7,代码来源:miscutils.py

示例9: Robot

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]

#.........这里部分代码省略.........
    def waitForConnectMsg(self):
        cnctMsgFound = False
        while not cnctMsgFound:
            nextMsg = self.popMessage()
            if nextMsg != None:
                logger.info("Connected to robot: %s" % self.name)
                cnctMsgFound = True
            time.sleep(1)


    def connect(self):
        logger.debug("Opening socket to robot: (%d) %s @ %s:%d" % (self.robotId, self.name, self.ip, self.port))
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.ip, self.port))
        conn_msg = {"robotId": self.robotId,
                    "userAgentName":"LongCat",
                    "userAgentVersion":"1.1.1.1"
                    }
        conn_json = json.dumps(conn_msg) + '\n'
        logger.debug('sending connection data: %s' % conn_json)
        self.socket.sendall(conn_json)
        logger.debug('connection data sent')
        self.startMsgReader()
        self.waitForConnectMsg()


    def disconnect(self):
        self.socket.close()
        self.socket = None

    def send_cmd_set(self):
        if self.notConnected():
            print "!!! Robot cannot send command because it isn't connected."
            return

        if len(self.cmd_dict) > 0:
            cmd_set = {"typ":"RobotCommandSet","data":self.cmd_dict}
            json_cmd = json.dumps(cmd_set) + '\n'
            logger.debug ("sending command set: %s",  json_cmd)
            self.socket.sendall(json_cmd)
            self.cmd_dict = {}

    def set_left_ear_rgb(self, r, g, b):
        self.cmd_dict[102] = {"r":r, "g":g, "b":b}

    def set_right_ear_rgb(self, r, g, b):
        self.cmd_dict[103] = {"r":r, "g":g, "b":b}

    def set_chest_rgb(self, w, d, x):
        self.cmd_dict[104] = {"r":w, "g":d, "b":x}

    def pan_head(self, degree):
        self.cmd_dict[203] = {"degree":degree}

    def tilt_head(self, degree):
        self.cmd_dict[202] = {"degree":degree}

    def lin_ang_body(self, speed_linear, speed_angular_rad, acc_linear, acc_angular):
        self.cmd_dict[204] = {"linear_cm_s":speed_linear, "angular_cm_s":speed_angular_rad, "linear_acc_cm_s_s":acc_linear, "angular_acc_deg_s_s":acc_angular}

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return "Robot(id: %d, name: %s, personalityColor: %s, isConnected: %s)" % (self.robotId, self.name, self.personalityColor, self.isConnected())

    def readNextMsg(self):
        logger.debug("socket.recv(%d)" % BUFF_SIZE)
        self.msgBuffer += self.socket.recv(BUFF_SIZE)
        index = self.msgBuffer.find('\n')
        logger.debug("index: %d, msgBuffer length: %d", index, len(self.msgBuffer))
        while index > 0:
            msgStr = self.msgBuffer[0:index]
            self.msgBuffer = self.msgBuffer[index + 1:]
            self.msgCnt += 1
            msg = json.loads(msgStr)
            logger.debug("eventType: %s", msg['event'])
            self.addMessage(msg)
            index = self.msgBuffer.find('\n')

    def addMessage(self, msg):
        with self.msgLock:
            self.msgs.insert(0,msg)
            self.msgs = self.msgs[0:10]
            return len(self.msgs)

    def popMessage(self):
        with self.msgLock:
            try:
                return self.msgs.pop()
            except IndexError:
                return None

    def startMsgReader(self):
        if self.msgReader != None:
            self.msgReader.cancel()
        self.msgReader = Timer(.03, self.readNextMsg)
        self.msgReader.setName("%s-msg-reader" % self.name)
        self.msgReader.setDaemon(True)
        self.msgReader.start()
开发者ID:wsmidt,项目名称:RobotController,代码行数:104,代码来源:robot.py

示例10: Robot

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]

#.........这里部分代码省略.........
            self.socket.sendall(json_cmd)
            self.cmd_dict = {}
#---------------------------------------------------------------------------------------------------------------------------------------------#
#-All of the following commands are built in to the robot. Have there own unique IDs, and send themselves to a command set when you call them-#
#---------------------------------------------------------------------------------------------------------------------------------------------#

    def set_left_ear_rgb(self, r, g, b):
        """Left ear color function: takes 0-1 values for r:red, g:green, & b:blue in that order. 102 is the robot has built in commandID's which is what the 102 is for, so the robot knows 102 = set left ear color. Sends command to command set."""
        self.cmd_dict[102] = {"r":r, "g":g, "b":b}

    def set_right_ear_rgb(self, r, g, b):
        """Right ear color function takes same values as left ear color. ID: 103"""
        self.cmd_dict[103] = {"r":r, "g":g, "b":b}

    def set_chest_rgb(self, r, g, b):
        """Chest color function takes same values as left and right ear color. ID:104"""
        self.cmd_dict[104] = {"r":r, "g":g, "b":b}

    def pan_head(self, degree):
        """Function that turns head left to right. takes a degrees parameter. range from (-120(leftmost) to 120(rightmost)) ID: 203"""
        self.cmd_dict[203] = {"degree":degree}

    def tilt_head(self, degree):
        """Function that tilts heaad up and down. takes a degrees parameter. range from (-20(Downmost) to 7.5(upmost)) ID: 202"""
        self.cmd_dict[202] = {"degree":degree}

    def set_wheels(self, left_whl_velo, right_whl_velo):
        """Function that sets wheel speed. Takes a right and left wheel velocity parameter. Infinite range negative and positive, negative = backwards, positive = forwards. You can set each wheel at different velocities if you like. ID:211"""
        self.cmd_dict[211] = {"right_cm_s": right_whl_velo, "left_cm_s": left_whl_velo}

    def lin_ang_body(self, speed_linear, speed_angular_rad, acc_linear, acc_angular):
        """function that sets speed, intensity of turn, acceleration rate of speed and turn speed. speed (infinite neg. and pos.), turn (-12(left tight turn) to 12(right tight turn)), acceleration of speed and turn speed (1-1000). ID:204"""
        self.cmd_dict[204] = {"linear_cm_s":speed_linear, "angular_cm_s":speed_angular_rad, "linear_acc_cm_s_s":acc_linear, "angular_acc_deg_s_s":acc_angular}

    def set_eye(self, eye_on):
        """Function that sets eye lights on or off.   ID:100"""
        self.cmd_dict[100] = {"index": [eye_on for x in range(0, 12)]}

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return "Robot(id: %d, name: %s, personalityColor: %s, isConnected: %s)" % (self.robotId, self.name, self.personalityColor, self.isConnected())

    def readAndSched(self):
        """Function  that reads messages recieved from robot, Keeps reading data constantly keeping you up to date with robot."""
        try:
            logger.debug("socket.recv(%d)" % BUFF_SIZE)
            self.msgBuffer += self.socket.recv(BUFF_SIZE)
            logger.debug(self.msgBuffer)
            index = self.msgBuffer.find('\n')
            logger.debug("index: %d, msgBuffer length: %d", index, len(self.msgBuffer))
            while index > 0:
                msgStr = self.msgBuffer[0:index]
                self.msgBuffer = self.msgBuffer[index + 1:]
                self.msgCnt += 1
                msg = json.loads(msgStr)
                self.addMessage(msg)
                index = self.msgBuffer.find('\n')
        except err:
            logger.error('Error reading from socket: %s', err.message)

        self.schedMsgReader()

    def handleSensorSet(self, sensorSet):
        if msg['sensorId'] == '1001':
            self.isButtonMainPressed = msg['pressed']
        if msg['sensorId'] == '1002':
            self.isbutton1Pressed = msg['Pressed']
        if msg['sensorId'] == '1003':
            self.isButton2Pressed = msg['Pressed']
        if msg['sensorId'] == '1004':
            self.isButton3Pressed = msg['Pressed']
        

    def addMessage(self, msg):
        """Function that only reads last 10 messages, taking one off the end and adding one to the beginning"""
        with self.msgLock:
            self.msgs.insert(0,msg)
            self.msgs = self.msgs[0:10]
            if msg['event'] == 'RobotSensortSetUpdated':
                handleSensorSet(msg['data']['sensorSet'])
            return len(self.msgs)

    def popMessage(self):
        """Function that pops a message off the list after it is read."""
        with self.msgLock:
            try:
                return self.msgs.pop()
            except IndexError:
                return None

    def schedMsgReader(self):
        """Function that starts reading messages and waits a certain amount of time then reads another."""
        if self.msgReader != None:
            self.msgReader.cancel()
        self.msgReader = Timer(.03, self.readAndSched)
        self.msgReader.setName("%s-msg-reader" % self.name)
        self.msgReader.setDaemon(True)
        self.msgReader.start()
开发者ID:Snappdizzle,项目名称:RobotController,代码行数:104,代码来源:robot.py

示例11: run_test

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
    def run_test(self): #{
        ue_tests = []
        max_duration = 0
        is_logging = self.__globals['logging']
        
        # Set up test-specific log directories, if user indicated logging was needed:
        if is_logging: # User wants logging
            if not os.path.exists(self.__globals['logdir']): os.mkdir(self.__globals['logdir'])
            test_logs = 'LoadTestLogs_' + str(datetime.now().strftime('%d-%m-%Y_%H%M%S'))
            test_logs_abs = os.path.join(self.__globals['logdir'], test_logs)
            os.mkdir(test_logs_abs)
        
        # Now loop through each UE config
        for ue_config in self.__ue_configs:
            ue_ip = self.__env.get_addr_of(ue_config['adaptername'])
            
            # Set up ue-specific log directories, if user indicated logging was needed:
            if is_logging: # User wants logging
                ue_logs = ue_config['adaptername'] + '_' + str(datetime.now().strftime('%d-%m-%Y_%H%M%S'))
                ue_logs_abs = os.path.join(test_logs_abs, ue_logs)
                os.mkdir(ue_logs_abs)
                
            # Convenience booleans for test_config and run_ue_test methods
            is_dl = False
            is_ul = False
            if ue_config['testtype'] == 'DL' or ue_config['testtype'] == 'SIM': is_dl = True
            if ue_config['testtype'] == 'UL' or ue_config['testtype'] == 'SIM': is_ul = True
            
            # Now get the test configs
            phase0_ue_test_config = self.get_test_config(ue_config, ue_ip, 0, is_dl, is_ul)
            phase1_ue_test_config = self.get_test_config(ue_config, ue_ip, 1, is_dl, is_ul)
            
            # Set up UE-specific log file path and file name prefix attributes, if user indicated logging was needed:
            if is_logging: # User wants logging
                phase0_ue_test_config['logpath'] = ue_logs_abs
                phase0_ue_test_config['logname'] = self.__globals['logprefix'] + ue_config['adaptername'] + '_Phase0'
                phase1_ue_test_config['logpath'] = ue_logs_abs
                phase1_ue_test_config['logname'] = self.__globals['logprefix'] + ue_config['adaptername'] + '_Phase1'
            
            # max_duration should contain the highest duration value from all UE tests
            # If the UE test is TCP then the total test duration is t1
            # If the UE test is UDP then the total test duration is t2
            if ue_config['traffictype'] == 'UDP':
                if int(ue_config['t2']) > max_duration: max_duration = int(ue_config['t2'])
            else:
                if int(ue_config['t1']) > max_duration: max_duration = int(ue_config['t1'])
            # Create Timer threads for each phase, delayed by the phase delay, passing in test_config and the interrupt event:
            phase0Process = Timer(phase0_ue_test_config['delay'], run_ue_test, [self.__interrupt_event, phase0_ue_test_config, is_dl, is_ul, is_logging])
            # Name the threads for debug purposes
            phase0Process.setName(ue_config['adaptername'] + '-phase0')
            phase1Process = Timer(phase1_ue_test_config['delay'], run_ue_test, [self.__interrupt_event, phase1_ue_test_config, is_dl, is_ul, is_logging])
            phase1Process.setName(ue_config['adaptername'] + '-phase1')
            # And add it to the list of threads:
            # All the tests are started at the same time, but are timed to start when needed using Timer threads:
            ue_tests.append(phase0Process)
            # Only add Phase 1 if testing UDP:
            if ue_config['traffictype'] == 'UDP': ue_tests.append(phase1Process)

        # Now run all the threads together:
        for t in ue_tests:
            t.start()
        try:
            # Wait for end of test, or until user hits Ctrl-C
            time.sleep(max_duration + 5)
            logging.debug('Total test waiting finished after ' + str(max_duration + 5) + ' seconds')
        except KeyboardInterrupt:
            # Inform all the threads an interrupt was encountered:
            self.__interrupt_event.set()
            # And cancel any Timer threads still waiting:
            for t in ue_tests: t.cancel()
            logging.warning('Process interrupted by user.\n')
            logging.warning('Tearing down processes and closing logs...\n')
开发者ID:olithomas,项目名称:multi-interface-iperf,代码行数:74,代码来源:TestInstance.py

示例12: basicConfig

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
#!/usr/bin/env python3
# timerthreads.py - timer threads
from threading import Timer
from time import sleep
from logging import basicConfig, debug, DEBUG

basicConfig(level=DEBUG, format="(%(threadName)s) %(message)s",)

def myThread():
    debug("myThread running")

thread1 = Timer(3, myThread)
thread1.setName("Thread1")
thread2 = Timer(3, myThread)
thread2.setName("Thread2")

debug("starting timers")
thread1.start()
thread2.start()

debug("waiting before canceling %s", thread2.getName())
sleep(2)
debug("canceling %s", thread2.getName())
thread2.cancel()

print("Main thread is done")

##################################################
#
#     $ timerthreads.py
#     (MainThread) starting timers
开发者ID:tamle022276,项目名称:python,代码行数:33,代码来源:timerthreads.py

示例13: MssqlConnection

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
    try:
        db_inst = MssqlConnection()
        room_dict = db_inst.room_id2desc
        db_inst.transfor_absolute_time()
    except Exception:
        log_msg = 'Something wrong with the database when try transforing absolute time !!!'
        log_handler.error(log_msg)
        return ERR

    pointer = 0
    timer = Timer(THRESHOLD_LOAD_CYCLE, timer_work)
    while not stopEvent.isSet():
        dbIsReady = MssqlConnection.test_connection()
        if dbIsReady == SUC:
            timer = Timer(THRESHOLD_LOAD_CYCLE, timer_work)
            timer.setName(THREAD_POLICY)
            timer.start()
            while timer.isAlive():
                sleep(0.1)
        else:
            log_msg = 'Something wrong with the database, system will reconnect in %d seconds !!!' %db_reconnect_cycle[pointer]
            log_handler.error(log_msg)
            sleep(db_reconnect_cycle[pointer])
            pointer = (pointer + 1) % len(db_reconnect_cycle)
    timer.cancel()

    log_msg = 'Load Threshold Thread shutdown and cleaned! '
    log_handler.work(log_msg)
#     log_manager.add_work_log(log_msg, sys._getframe().f_code.co_name)

    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
开发者ID:JohnChain,项目名称:mushroom,代码行数:33,代码来源:load_threshold.py

示例14: schedule

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setName [as 别名]
 def schedule(function: callable) -> None:
     interval = 5 * 60
     timer = Timer(interval, function)
     timer.setName('Communication Thread ' + str(randint(0, 10000)))
     timer.start()
开发者ID:Sarkel,项目名称:pite-laboratory,代码行数:7,代码来源:communication.py


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