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


Python Timer.Timer类代码示例

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


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

示例1: widget

 def widget(self, d):
     LOGFP       = open("log.create-test-case.txt", "a")
     LOGFP.write("\n")
     LOGFP.write("-----------------------------------------------\n")
     LOGFP.write("%s/tools/create-test-case.sh ocsp-1 %s\n" % (self._pwd, d))
     LOGFP.write("-----------------------------------------------\n")
     LOGFP.close()
     LOGFP       = open("log.sign-widget.txt", "a")
     
     handle      = Popen("%s/tools/create-test-case-modified.sh ocsp-1 %s" % (self._pwd, d), shell=True, stdout=LOGFP, stderr=LOGFP, cwd="%s/tools" % (self._pwd), close_fds=True)
     runTimer    = Timer()
     
     while True:
         if (runTimer.elapsed() > 60):
             handle.terminate()
         # if
         
         handle.poll()
         
         if (handle.returncode != None):
             break
         # if
     # while
     
     LOGFP.write("-------------------- done --------------------\n")
     LOGFP.close()
     print " - created widget [returncode: %d]" % (handle.returncode)
开发者ID:prestocore,项目名称:browser,代码行数:27,代码来源:auto.py

示例2: edit_main

def edit_main(screen):
    #pygame.init()
    #screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('LevelEdit')
    pygame.mouse.set_visible(1)
    clock = pygame.time.Clock()
    level = EditLevel(2000, 800, 'objects1.ini', DATA_PATH)
    pygame.display.flip()
    screen.blit(level.background, (0, 0))

    while 1:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == QUIT_EVENT:
                return
            if event.type == pygame.KEYUP:
                level.key_input(event.key)
            if event.type == pygame.MOUSEBUTTONUP:
                level.mouse_input(event)
            if event.type > pygame.USEREVENT:
                Timer.handle_event(event.type)

        level.update()
        level.draw(screen)
        level.gui_manager.draw(screen)
        pygame.display.flip()

    pygame.display.quit()
    pygame.quit()
开发者ID:v0ided,项目名称:FirstPyGame,代码行数:31,代码来源:EditMain.py

示例3: GameCounter

class GameCounter():
    def __init__(self):
        self.background = pygame.image.load('resources/background_pause.png').convert_alpha()

        self.counter = 10000
        self.state = True
        self.timer = Timer()

        self.font = pygame.font.Font('resources/ThrowMyHandsUpintheAirBold.ttf',300)
        self.text_counter = Text(self.font,self.counter,(255,255,255),SCREEN_WIDTH/2,SCREEN_HEIGHT/2)

        self.timer.start()

    def update(self,screen):
        while self.state:
            self.counter -= self.timer.time() * 100

            if self.counter < 0:
                self.state = False
                self.timer.stop()
                scene.timer.start()

            #make text in update, why is a object that renew
            self.text_counter = Text(self.font,int(math.ceil(self.counter/4000)),(255,255,255),SCREEN_WIDTH/2,SCREEN_HEIGHT/2)
            self._draw(screen)

    def _draw(self,screen):
        #Doesnt loss images of previous scene
        screen.blit(scene.background,(0,0))
        screen.blit(scene.title_shadow,(0,0))
        scene.level_title.draw(screen)

        screen.blit(self.background,(0,0))
        self.text_counter.draw(screen)
        pygame.display.flip()
开发者ID:irvingprog,项目名称:WITS,代码行数:35,代码来源:main.py

示例4: Muerta

class Muerta(Sprite):

    def __init__(self, pos, escala, TIME):

        Sprite.__init__(self)

        path = os.path.join(BASE_PATH, "Imagenes", "muerta.png")
        imagen = pygame.image.load(path)
        imagen_escalada = pygame.transform.scale(imagen, escala)
        self.image = imagen_escalada.convert_alpha()
        self.rect = self.image.get_rect()

        self.image = pygame.transform.rotate(self.image, -pos[0])
        self.rect.centerx = pos[1]
        self.rect.centery = pos[2]

        self.timer = Timer(TIME)
        self.edad = {
            "Años": 0,
            "Dias": 0,
            "Horas": 0}
        self.timer.connect("new-time", self.__update_time)

    def __update_time(self, widget, _dict):
        self.edad = dict(_dict)
        if self.edad["Dias"] >= 3:
            self.morir()

    def morir(self):
        self.timer.salir()
        self.kill()
开发者ID:fdanesse,项目名称:Bichos,代码行数:31,代码来源:Cucaracha.py

示例5: runGrid

def runGrid(passCount, filename='lists/binaries2.dat'):
	'''
	Wrapper function to run the binary mofel fitting grid.

	:param passCount: [in] The maximum amount of passes to run on the grid
	:param filename: [in] The filename of the file containing a list of targets field and APOGEE ID's to use
	'''
	timer = Timer()
	timer.start()
	# Prep Grid
	locationIDs, apogeeIDs = np.loadtxt(filename, unpack=True, delimiter=',', dtype=str)
	targetCount = len(locationIDs)
	gridParams = [GridParam(locationIDs[i], apogeeIDs[i]) for i in range(targetCount)]
	minimizedVisitParams = [np.array([]) for i in range(targetCount)]

	# Use past results
	# checkPreviousData(gridParams)

	grid(passCount, gridParams, minimizedVisitParams)
	writeGridToFile(gridParams)
	for i in range(len(minimizedVisitParams)):
		filename = 'lists/chi2/' + minimizedVisitParams[i][0].locationID + '/' + minimizedVisitParams[i][0].apogeeID + '.lis'
		if not os.path.exists('lists/chi2/' + minimizedVisitParams[i][0].locationID + '/'):
			os.makedirs('lists/chi2/' + minimizedVisitParams[i][0].locationID + '/')
		writeGridToFile(minimizedVisitParams[i], filename=filename)

	print('Total run time: ' + str(round(timer.end(), 2)) + str('s'))
开发者ID:xmannyh,项目名称:apogee_binary_model,代码行数:27,代码来源:Grid.py

示例6: run

    def run(self, options):
        config = Config()
        config.keep_results = options['keep_results']
        config.create_diffs = options['create_diffs']
        config.update_refs = options['update_refs']

        t = Timer()
        docs = options['tests']
        docs_dir = options['docs_dir']

        if len(docs) == 1:
            if os.path.isdir(docs[0]):
                if docs_dir is None:
                    docs_dir = docs[0]
                if docs_dir == docs[0]:
                    docs = []
            else:
                if docs_dir is None:
                    docs_dir = os.path.dirname(docs[0])
        else:
            if docs_dir is None:
                docs_dir = os.path.commonprefix(docs).rpartition(os.path.sep)[0]

        tests = TestRun(docs_dir, options['refs_dir'], options['out_dir'])
        status = tests.run_tests(docs)
        tests.summary()
        get_printer().printout_ln("Tests run in %s" % (t.elapsed_str()))

        return status
开发者ID:BlueBrain,项目名称:Poppler,代码行数:29,代码来源:run-tests.py

示例7: monitor

def monitor():
    """Send discovery and monitor messages, and capture any responses"""

    # Define the schedule of message polling
    sendSwitchTimer    = Timer(5, 1)   # every n seconds offset by initial 1
    switch_state       = 0             # OFF
    radio.receiver()
    decoded            = None

    while True:
        # See if there is a payload, and if there is, process it
        if radio.isReceiveWaiting():
            #trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenHEMS.decode(payload)
            except OpenHEMS.OpenHEMSException as e:
                warning("Can't decode payload:" + str(e))
                continue
                      
            OpenHEMS.showMessage(decoded)
            updateDirectory(decoded)
            logMessage(decoded)
            
            #TODO: Should remember report time of each device,
            #and reschedule command messages to avoid their transmit slot
            #making it less likely to miss an incoming message due to
            #the radio being in transmit mode

            # handle messages with zero recs in them silently
            #trace(decoded)
            if len(decoded["recs"]) == 0:
                print("Empty record:%s" % decoded)
            else:
                # assume only 1 rec in a join, for now
                if decoded["recs"][0]["paramid"] == OpenHEMS.PARAM_JOIN:
                    #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                    # send back a JOIN ACK, so that join light stops flashing
                    response = OpenHEMS.alterMessage(JOIN_ACK_MESSAGE,
                        header_mfrid=decoded["header"]["mfrid"],
                        header_productid=decoded["header"]["productid"],
                        header_sensorid=decoded["header"]["sensorid"])
                    p = OpenHEMS.encode(response)
                    radio.transmitter()
                    radio.transmit(p)
                    radio.receiver()

        if sendSwitchTimer.check() and decoded != None:
            request = OpenHEMS.alterMessage(SWITCH_MESSAGE,
                header_sensorid=decoded["header"]["sensorid"],
                recs_0_value=switch_state)
            p = OpenHEMS.encode(request)
            radio.transmitter()
            radio.transmit(p)
            radio.receiver()
            switch_state = (switch_state+1) % 2 # toggle
开发者ID:davidjesse,项目名称:pyenergenie,代码行数:56,代码来源:monitor.py

示例8: testFrameLimiter

    def testFrameLimiter(self):
        t = Timer(fps = 60)

        fps = []
        while t.frame < 100:
            ticks = list(t.advanceFrame())
            fps.append(t.fpsEstimate)

        fps = fps[30:]
        avgFps = sum(fps) / len(fps)
        assert 0.8 * t.fps < avgFps < 1.2 * t.fps
开发者ID:Hawkheart,项目名称:fof-reborn,代码行数:11,代码来源:TimerTest.py

示例9: test1

def test1():
    """Test Timer class."""
    from time import sleep
    from datetime import timedelta
    from Timer import Timer

    timer = Timer()
    sleep(0.001)
    assert timer.get() > timedelta(seconds=0.001)
    sleep(0.001)
    assert timer.get() > timedelta(seconds=0.001)
    assert timer.getTotal() > timedelta(seconds=0.002)
开发者ID:,项目名称:,代码行数:12,代码来源:

示例10: __init__

    def __init__(self, var_dict):
        BaseObject.__init__(self, var_dict)
        self.type = PLAYER
        self.xvel = 0
        self.yvel = 0
        self.jumpvel = 1
        self.walkvel = 0.05
        self.maxXvel = 2.3
        self.maxYvel = 8
        self.direction = DIR_RIGHT
        self.iswalking = False
        self.on_object = None
        self.col_object = None
        self.jump_state = NOT_JUMPING
        self.airborne = True
        self.j_delay_timer = Timer(50, self.__next_jump_state, False)
        self.jump_timer = Timer(240, self.__next_jump_state, False)
        self._layer = 10
        #Array of objects currently colliding with rect - Tracks objects that are possible to interact with
        self.pos_interact = []
        self.held_item = None
        self.drop_item = None
        self.collidable = True
        self.held_ofs_x = 0.0
        self.held_ofs_y = 0.0
        self.obey_gravity = True
        self.visible = True

        self.idle_files = var_dict['idle_files'].split(',')
        self.idle_times = var_dict['idle_times'].split(',')
        self.jump_files = var_dict['jump_files'].split(',')
        self.jump_times = var_dict['jump_times'].split(',')
        self.walk_files = var_dict['walk_files'].split(',')
        self.walk_times = var_dict['walk_times'].split(',')
        self.idle_anim = Animation(self.idle_files, self.idle_times)
        self.jumping_anim = Animation(self.jump_files, self.jump_times)
        self.walking_anim = Animation(self.walk_files, self.walk_times)
        self.walking_anim.set_colorkey((255, 255, 255))

        if var_dict['w'] == 0 or var_dict['h'] == 0:
            self.rect.w = self.idle_anim.getRect().w
            self.rect.h = self.idle_anim.getRect().h
        else:
            pass
            #Needs to scale all animations while keeping aspect ratio.
            #self.walking_anim.scale((var_dict['w'], var_dict['h']))
            #self.jumping_anim.scale((var_dict['w'], var_dict['h']))
        self.anim_player = Animation_Player()
        self.anim_player.add(self.walking_anim, WALK_ANIM)
        self.anim_player.add(self.jumping_anim, JUMP_ANIM)
        self.anim_player.add(self.idle_anim, IDLE_ANIM)
        self.anim_player.set(IDLE_ANIM, True)
开发者ID:v0ided,项目名称:FirstPyGame,代码行数:52,代码来源:Player.py

示例11: __init__

 def __init__(self, var_dict):
     LevelObject.__init__(self, var_dict)
     self.type = BUILD_PROC
     str_input = var_dict['input']
     str_output = var_dict['output']
     self.input_items = [x.strip() for x in str_input.split(',')]
     self.output_items = [x.strip() for x in str_output.split(',')]
     self.length = to_num(var_dict['time'])
     self.delay_timer = Timer(5, self._ready)
     self.build_timer = Timer(self.length, self._finish)
     self.ready = True
     self.built = []  # list of output items that need to be spawned into the level
     self.input_area = self.rect  # required input parts must collide with this rect to start build
     self.output_area = pygame.Rect(self.rect.right, self.rect.bottom, 200, 100)  # items with output in this rect
开发者ID:v0ided,项目名称:FirstPyGame,代码行数:14,代码来源:BuildProcess.py

示例12: monitor

def monitor():
    """Send discovery and monitor messages, and capture any responses"""

    # Define the schedule of message polling
    sendSwitchTimer    = Timer(60, 1)   # every n seconds offset by initial 1
    switch_state       = 0             # OFF
    radio.receiver()
    decoded            = None

    while True:
        # See if there is a payload, and if there is, process it
        if radio.isReceiveWaiting():
            trace("receiving payload")
            payload = radio.receive()
            try:
                decoded = OpenHEMS.decode(payload)
            except OpenHEMS.OpenHEMSException as e:
                print("Can't decode payload:" + str(e))
                continue
                      
            OpenHEMS.showMessage(decoded)
            updateDirectory(decoded)
            logMessage(decoded)
            
            #TODO: Should remember report time of each device,
            #and reschedule command messages to avoid their transmit slot
            #making it less likely to miss an incoming message due to
            #the radio being in transmit mode

            # assume only 1 rec in a join, for now
            if len(decoded["recs"])>0 and decoded["recs"][0]["paramid"] == OpenHEMS.PARAM_JOIN:
                #TODO: write OpenHEMS.getFromMessage("header_mfrid")
                response = OpenHEMS.alterMessage(MESSAGE_JOIN_ACK,
                    header_mfrid=decoded["header"]["mfrid"],
                    header_productid=decoded["header"]["productid"],
                    header_sensorid=decoded["header"]["sensorid"])
                p = OpenHEMS.encode(response)
                radio.transmitter()
                radio.transmit(p)
                radio.receiver()

        if sendSwitchTimer.check() and decoded != None and decoded["header"]["productid"] in [Devices.PRODUCTID_C1_MONITOR, Devices.PRODUCTID_R1_MONITOR_AND_CONTROL]:
            request = OpenHEMS.alterMessage(MESSAGE_SWITCH,
                header_sensorid=decoded["header"]["sensorid"],
                recs_0_value=switch_state)
            p = OpenHEMS.encode(request)
            radio.transmitter()
            radio.transmit(p)
            radio.receiver()
            switch_state = (switch_state+1) % 2 # toggle
开发者ID:sjhx,项目名称:pyenergenie,代码行数:50,代码来源:monitor.py

示例13: updateK

    def updateK(self):
        [fro, to, pts] = eval(self.animationKEntry.get())

        self.K = np.linspace(fro, to, pts)
        t = np.linspace(0, float(self.timeEntry.get()), TIME_PTS)

        self.x_main = np.zeros((len(self.K), TIME_PTS, len(self.inpt.PlantFrame.getA())))
        self.u_main = np.zeros((len(self.K), TIME_PTS, self.inpt.PlantFrame.getB().shape[1]))

        for i in range(len(self.K)):
            Timer.reset(t)
            (x, u) = self.inpt.getX(t, self.Kset + [self.K[i]])

            self.u_main[i, :, :] = u
            self.x_main[i, :, :] = x
开发者ID:fgonz012,项目名称:Control-System-Application,代码行数:15,代码来源:PlotFrame.py

示例14: __init__

	def __init__(self, fname):

		self.tdl = ToDoList(fname)
		self.taskList = self.tdl.getTaskList()

		random.shuffle(self.taskList)
		self.timer = Timer()
开发者ID:tgvaughan,项目名称:taskmuxer,代码行数:7,代码来源:Schedule.py

示例15: MainView

class MainView(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.label = QLabel("Alarm!", self)
        
        
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)
        
        self.timer = Timer()
        
        self.add_button_timer(10)
        
        self.add_button("&Quit", SLOT("quit()"))
        
        self.setLayout(self.layout)
        
    def add_button_timer(self, m):
        button = QPushButton("%dmin"%m, self)
        button.clicked.connect(lambda: self.timer.reset(m))
        self.layout.addWidget(button)
        
        
    def add_button(self, msg, slot):
        button = QPushButton(msg, self)
        self.connect(button, SIGNAL("clicked()"), QCoreApplication.instance(), slot)
        self.layout.addWidget(button)
开发者ID:shallwexuewei,项目名称:Alarm,代码行数:27,代码来源:MainView.py


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