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


Python Timer.start方法代码示例

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


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

示例1: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
class PhysicsManager:
	def __init__(self):
		self.timer = Timer(PHYSICS_TIMER_INTERVAL, "physics_timer")
		self.started = False
		self.tasks = []

	def __del__(self):
		self.timer.stop()

	def update(self):
		if len(self.tasks) == 0:
			self.started = False
			self.timer.stop()
			return

		for task in self.tasks:
			vy = task.velocity[1]
			for i in [0, 1, -1]:
				v0 = task.velocity[i]
				task.velocity[i] += task.accel[i] * PHYSICS_TIMER_INTERVAL
				task.position[i] += (v0 + task.velocity[i]) / 2.0 * PHYSICS_TIMER_INTERVAL
			task.falling_time += PHYSICS_TIMER_INTERVAL
			task.falling_height += abs(task.velocity[1] + vy) / 2.0 * PHYSICS_TIMER_INTERVAL
			task.obj.update_position(task.position)

		self.timer.add_task(PHYSICS_TICK, self.update)

	# do physics to an object which has:
	#   * method update_position(position) to update its position
	def do_physics(self, position, accel, obj):
		self.tasks.append(PhysicsTask(position, accel, obj))
		if not self.started:
			self.started = True
			self.timer.add_task(PHYSICS_TICK, self.update)
			self.timer.start()
开发者ID:boskee,项目名称:Minecraft,代码行数:37,代码来源:physics.py

示例2: stopall

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
    def stopall(self, timeout=10):
        """
        Stops all known child processes by calling 
        """
        all = InProgressAll(*[process.stop() for process in self.processes.keys()])
        # Normally we yield InProgressAll objects and they get implicitly connected
        # by the coroutine code.  We're not doing that here, so we connect a dummy
        # handler so the underlying IPs (the processes) get connected to the IPAll.
        all.connect(lambda *args: None)

        # XXX: I've observed SIGCHLD either not be signaled or be missed
        # with stopall() (but not so far any other time).  So this kludge
        # tries to reap all processes every 0.1s while we're killing child
        # processes.
        poll_timer = Timer(lambda: [process._check_dead() for process in self.processes.keys()])
        poll_timer.start(0.1)
        while not all.finished:
            main.step()
        poll_timer.stop()

        # Handle and log any unhandled exceptions from stop() (i.e. child
        # failed to die)
        for process in self.processes:
            try:
                inprogress(process).result
            except SystemError, e:
                log.error(e.message)
开发者ID:jpmunz,项目名称:smartplayer,代码行数:29,代码来源:process.py

示例3: start

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
def start():
    global DATASTORE, URL, KEY
    
    default_tmp = "/tmp/itzod"
    if sys.platform.startswith('win'):
        default_tmp = "C:\\temp\\itzod"
        
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Web server Host address to bind to", 
                        default="0.0.0.0", action="store", required=False)
    parser.add_argument("-p", "--port", help="Web server Port to bind to", 
                        default=8000, action="store", required=False)
    parser.add_argument("-k", "--key", help="Itzod User APIKey for accessing json urls",
                        action="store", required=True)
    parser.add_argument("-u", "--url", help="Base itzod URL for accessing api",
                        default="https://pool.itzod.ru/apiex.php",
                        action="store", required=False)
    parser.add_argument("-d", "--datadir", help="Data directory to store state",
                        default=default_tmp,
                        action="store", required=False)
    args = parser.parse_args()
    
    logging.basicConfig()
    DATASTORE = Datastore(args.datadir)
    URL = args.url
    KEY = args.key
    
    t = Timer(60, poll, ())
    t.start()
    
    run(host=args.host, port=args.port, reloader=True)
开发者ID:San3ko,项目名称:itzodmon,代码行数:33,代码来源:web.py

示例4: Fuzzie

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
class Fuzzie(TextEntity):
	def __init__(self, layer, vel_x, vel_y):
		TextEntity.__init__(self, None, layer, char = '*')
		#self.setPos(self.pos_x, s.pos_y)
		self.vel_x = vel_x
		self.vel_y = vel_y
		self.visible = True
		self.liveTimer = Timer()
		self.liveTimer.start()
		self.name = 'Fuzzie'
	
	def death(self, attacker=None, deathtype=None):
		self.health = -1

	def think(self, frameDT):
		if len(self.touching): self.collideHandler()
		if not self.health: self.death()

	def collideHandler(self):
		for partner in self.touching:
			if partner[0]:
				if partner[0].getChar() == '+':
					#print "Hit by bullet!"
					self.health = 0
		self.touching = []
开发者ID:spekode,项目名称:2dengine1,代码行数:27,代码来源:player.py

示例5: main

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
def main():
    interval = 5

    if len(sys.argv) > 1:
        script_path = sys.argv[1]
        sys.argv = sys.argv[1:]
    else:
        print >> sys.stderr, "usage: python -m tripod.sampler ./script_path.py"
        print >> sys.stderr, "(Default interval: %f seconds. Override with TRIPOD_INTERVAL env var)" % interval
        sys.exit(1)

    interval = float(os.environ.get("TRIPOD_INTERVAL", interval))

    timer = Timer()
    timer.setDaemon(True)
    timer.start()

    # dump to file:
    fd, fn = tempfile.mkstemp(prefix='slow_process_', suffix='.log', dir='/tmp')

    print >> sys.stderr, "[Tripod] Sampling every %f seconds" % interval
    print >> sys.stderr, "[Tripod] Writing output to:", fn

    timer.run_later(peek, interval, fd, thread.get_ident(), dt.datetime.utcnow())

    exit_code = 0
    try:
        with open(script_path) as f:
            global __file__
            __file__ = script_path
            exec f.read() in globals(), globals()
    except SystemExit, e:
        exit_code = e.code
开发者ID:shayne,项目名称:tripod,代码行数:35,代码来源:sampler.py

示例6: run

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
 def run(self):
     timer = Timer()
     timer.start()
         
     # Create list of search urls
     search_urls = []
     filter = Filter(self.filter, self.startpage, self.maxpages)
     for page in range(self.startpage, self.startpage + self.maxpages):
         search_urls.append(filter.create_filter_url((page - 1) * 10))
     
     # Create pool of worker threads
     pool = ThreadPool(4)
     # Open the urls in their own threads
     organisaties = pool.map(unwrap_self_process_search, zip([self] * len(search_urls), search_urls))
     pool.close()
     pool.join()
 
     results = {}
     results["organisaties"] = self.consolidate(organisaties)
     
     timer.stop()
     
     results["stats"] = { "exectime": timer.exectime(), "matches": { "total": str(self.search_results["results"]), "pages": str(self.search_results["pages"]) }, "read": { "page_from": str(self.startpage), "page_to": str(self.maxpages) } }
     
     return results
开发者ID:nidkil,项目名称:python-kvk-web-scraper,代码行数:27,代码来源:search.py

示例7: save

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
    def save(self,file):
        """
            Arguments:
                
                file: where to save (utf-8 encoding)

            Examples:
                
                ngrams.save("myfile")
        """

        file = self.__test_file(file,'w')
        n_word = len(self)

        buffer = ""

        sys.stderr.write("Saving the %i-grams...\n" % self.__max_arity)

        t = Timer(n_word,out=sys.stderr)
        t.start()
        for i in range(self.__max_arity):
            for word in self.__get_sorted_grams(i,(0,i+1)):
                buffer += "#".join(word)+"%"+str(self.__ngrams[i][word])+"\n"

                if len(buffer) > 1000:
                    file.write(buffer)
                    buffer = ""

                t.print_update(1)

        file.write(buffer)
        file.close()
开发者ID:bouthilx,项目名称:toiledemots,代码行数:34,代码来源:ngrams.py

示例8: acquisition

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
def acquisition(config):

    timer = Timer()
    getch = _Getch()
    last_char = ""
    last_char2 = ""
    nl_count = 0
    bs_count = 0
    char_count = 0
    quit = False

    while not quit:
        # on lit un caractère
        my_char = getch()
        char_count += 1
        # saut de ligne:
        if my_char == "\r":
            print
            nl_count += 1
            # reset le dernier caractère
            last_char = ""
            last_char2 = ""
            # autre caractère
        else:
            nl_count = 0
            # caractère BACKSPACE
            if my_char == "\x08" or my_char == "\x7f":
                # on compte le nb de backspace pour les stats
                bs_count += 1
                # écrire un backspace déplace simplement le curseur
                # il faut effacer avec un espace
                sys.stdout.write("\x08 \x08")
                # reset le dernier caractère
                last_char = ""
            else:
                sys.stdout.write(my_char)

                # si un précédent caractère était présent
                if last_char != "":
                    # récupérer le temps entre deux frappes
                    t = timer.time()

                    # ajout dans la configuration si l'intervalle semble correct
                    if t < 1:
                        config.add(last_char + my_char, t)

                    if last_char2 != "":
                        config.add(last_char2 + last_char + my_char, t)
                        # sauvegarde du dernier caractère
                last_char2 = last_char
                last_char = my_char

                # deux appuis simultanés sur ENTER quittent la boucle
        if nl_count == 2:
            quit = True

            # reset du chronomètre
        timer.start()

    return float(bs_count) / float(char_count) * 100
开发者ID:Pawamoy-Sandbox,项目名称:magelli,代码行数:62,代码来源:acquisition.py

示例9: test_stop

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
 def test_stop(self):
     timer = Timer()
     time.sleep(5)
     timer.stop()
     time.sleep(3)
     timer.start()
     time.sleep(5)
     self.assertEqual(timer.get_counter(),10)
开发者ID:bcaccinolo,项目名称:fischer,代码行数:10,代码来源:test_timer.py

示例10: test_timer

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
 def test_timer(self):
     t = Timer()
     id = t.start();
     id1 = t.start();
     print("wheeeeee")
     t.end(id, "mooo")
     t.end(id1, "fooo")
     t.finish()
开发者ID:ccassler,项目名称:eutester,代码行数:10,代码来源:testtimer.py

示例11: KeywordClient

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
class KeywordClient():

    def __init__(self,server_url=""):
        self.server_url = server_url
        self.request_header = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        self.timer_started = False
        self.timer = Timer()

    def checkTimer(self):
        if not self.timer_started:
            self.timer.start()
            self.timer_started = True

    def resetTimer(self):
        self.timer_started = False
        self.timer.start()

    def getSettings(self):
        r = requests.get(self.server_url+'getSettings')
        return r.json()

    def sendCategories(self, categories):
        data = {'handle':'setCategories', 'categories':categories}
        red.publish('ambient', json.dumps(data))
        
    def addRelevantEntry(self, type, title, text, url, score, insert_before):
        self.checkTimer()
        data = {'handle':'addRelevantEntry','type':type,'entry_id': idFromTitle(title),'title':title,'text':text,'url':url,'score':score, 'insert_before': insert_before, 'time': float(self.timer.current_secs())}
        print data
        red.publish('ambient', json.dumps(data))

    def delRelevantEntry(self, type, title):
        self.checkTimer()
        data = {'handle':'delRelevantEntry','type':type,'title': title, 'entry_id': idFromTitle(title), 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def addUtterance(self, utterance, speaker):
        self.checkTimer()
        data = {'handle':'addUtterance','utterance':utterance,'speaker':speaker, 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def replaceLastUtterance(self, old_utterance, new_utterance, speaker):
        self.checkTimer()
        data = {'handle':'replaceLastUtterance','old_utterance':old_utterance,'utterance':new_utterance,'speaker':speaker, 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def completeUtterance(self, utterance, speaker):
        self.checkTimer()
        data = {'handle':'completeUtterance','utterance':utterance,'speaker':speaker , 'time': float(self.timer.current_secs())}
        print data
        red.publish('ambient_transcript_only', json.dumps(data))

    def reset(self):
        data = {'handle':'reset'}
        red.publish('ambient_transcript_only', json.dumps(data))
        self.resetTimer()
        r = requests.post(self.server_url+'reset', data=json.dumps(data), headers=self.request_header)
        return r.status_code
开发者ID:joneswack,项目名称:ambientsearch,代码行数:60,代码来源:bridge.py

示例12: add_location

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
 def add_location(self, pos = None):
     if pos is None:
         pos = helpers.parse_coords(self.location_str.get())
     pos = tuple(pos)
     styles = ["b", "g", "r", "c", "m", "y", "k"]
     threshold = 1e-4
     if len(pos) == 2:
         pos = pos[0], pos[1], 0.0
     if PROJECTIONS[self.opts.projection.get()] != '3d':
         pos = pos[0], pos[1], 0.0
         self.location_str.set("%0.4g, %0.4g" % (pos[0], pos[1]))
     else:
         self.location_str.set("%0.4g, %0.4g, %0.4g" % pos)
     #Search for a fixed point
     ## fp = self.system.find_fp(pos, threshold = 1e-4)
     ## if fp is not None:
     ##     fp_clean = tuple(np.round(fp, 3))
     ##     if not fp_clean in self.fixed_points:
     ##         self.fixed_points.add(fp_clean)
     ##         self.fig.draw_fp(fp_clean)
     ##         self.update_fig()
     ##         vel = self.system(fp_clean)
     ##         logging.info("Found a fixed point: %s %s\n" % (str(fp_clean), str(vel)))
     if pos in self.trajectories:
         logging.warning("Trajectory already exists.")
         self.status.info("Trajectory already exists.")
         return
     self.status.info("Computing trajectory...")
     try:
         t = Timer()
         t.start()
         traj = self.system.trajectory(pos, self.opts.tmax.get(), threshold = threshold,
             bidirectional = self.opts.reverse.get(), nsteps = 5 * (self.opts.tmax.get()/self.opts.dt.get()),
             max_step = self.opts.dt.get(), use_ode = True)
         t.stop()
         logging.debug("Computing trajectory (%d points) took %g seconds" % (len(traj.x), t.seconds()))
     except:
         pos_str = ", ".join(map(str, pos))
         logging.warning("Could not compute trajectory from: %s" % pos_str)
         logging.debug(traceback.format_exc())
         return
     #if traj.dist[-1] < 10*threshold:
     #    return
     self.trajectories[pos] = traj
     if traj.t[-1] > self.anim_tmax:
         self.anim_tmax = traj.t[-1]
     style = (len(self.trajectories) - 1) % len(styles)
     traj.style = styles[style]
     self.status.info("Drawing trajectory...")
     self.fig.add_trajectory(traj)
     self.status.clear()
     #self.fig.draw_trajectory(traj)
     self.fig.draw()
     self.last_loc = pos
开发者ID:grajkiran,项目名称:ezeplot,代码行数:56,代码来源:gui.py

示例13: start_timer

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
def start_timer(bot):
    """Set up schedule service for bot"""
    
    tm = Timer(bot) # Set up timer, with empty joblist

    # Repeatedly send PONG to keep
    tm.add_repeat(bot.sets['bot_ping_interval'], bot.send_ping, [])
    
    tm.log.info('Starting Timer..')
    tm.start()
    return tm
开发者ID:kimmobrunfeldt,项目名称:basicbro,代码行数:13,代码来源:bot.py

示例14: cluster_docs

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
def cluster_docs():
    timer = Timer()
    timer.start()
    from clustering.K_means import K_means
    c = K_means()
    c.clusterDocs()
    timer.end()

    return render_template('clustering_result.html',
        duration=timer.get_time_taken_pretty(),
        numclusters=len(c.centroidList)
    )
开发者ID:MJafarMashhadi,项目名称:MiniGoogle,代码行数:14,代码来源:ui.py

示例15: Bullet

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import start [as 别名]
class Bullet(TextEntity):
	def __init__(self, owner, layer, vel_x, vel_y):
		TextEntity.__init__(self, owner, layer, char = '+')
		self.setPos(owner.pos_x, owner.pos_y)
		self.setOldPos(owner.pos_x, owner.pos_y)
		self.resistance_x = 0
		self.resistance_y = 0
		self.vel_x = vel_x
		self.vel_y = vel_y
		self.visible = True
		self.liveTimer = Timer()
		self.liveTimer.start()
		self.name = 'Bullet'
	
	def death(self, attacker=None, deathtype=None):
		self.health = -1

	def collideHandler(self):
		for partner in self.touching:
			if partner[0]:
				if partner[0] == self.owner:
					pass # we don't hurt ourselves :D
				else:
					#print "Bullet collided with", partner[0]
					#self.pos_x = partner[1][0]
					#self.pos_y = partner[1][1]
					self.pos_x = self.oldpos_x
					self.pos_y = self.oldpos_y
					self.vel_x = 0
					self.vel_y = 0
					self.health = 0
			else:
				# hit the map
				#print "hit a wall"
				self.pos_x = self.oldpos_x
				self.pos_y = self.oldpos_y
				self.vel_x = 0
				self.vel_y = 0
				self.health = 0

		self.touching = []

	def think(self, frameDT):
		if len(self.touching): self.collideHandler()

		if self.liveTimer.elapsed() > 1000:
			#print "timed out!"
			self.health = 0

		if not self.health:
			#print "died!"
			self.death()
开发者ID:spekode,项目名称:2dengine1,代码行数:54,代码来源:player.py


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