本文整理汇总了Python中Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_3
def test_3(db,collectionName,search_doc,projection={},save=0,limit=0):
time_total=Timer()
time_total.start()
#****************
c= db[collectionName]
#search_doc={}
#search_doc["f1xxxxxxxx"]= search_str
#cursor=c.find(search_doc,projection)
if projection:
cursor=c.find(search_doc,projection).limit(limit)
else:
cursor=c.find(search_doc).limit(limit)
#cursor=c.find()
documentList=[]
if save:
documentList=list(cursor)
#documents=getAllDocuments(db,collectionName,1)
time_total.stop()
print("Total:{}, search time:{}".format(cursor.count(with_limit_and_skip=True),
time_total.elapsed))
# if limit:
# print("Total:{}, search time:{}".format(limit,time_total.elapsed))
# else:
# print("Total:{}, search time:{}".format(cursor.count(),time_total.elapsed))
return documentList
示例2: test_call_repeatedly
def test_call_repeatedly(self):
t = Timer()
try:
t.schedule.enter_after = Mock()
myfun = Mock()
myfun.__name__ = bytes_if_py2('myfun')
t.call_repeatedly(0.03, myfun)
assert t.schedule.enter_after.call_count == 1
args1, _ = t.schedule.enter_after.call_args_list[0]
sec1, tref1, _ = args1
assert sec1 == 0.03
tref1()
assert t.schedule.enter_after.call_count == 2
args2, _ = t.schedule.enter_after.call_args_list[1]
sec2, tref2, _ = args2
assert sec2 == 0.03
tref2.canceled = True
tref2()
assert t.schedule.enter_after.call_count == 2
finally:
t.stop()
示例3: test_2
def test_2(db,collectionName,save):
time_total=Timer()
time_total.start()
#****************
documents=getAllDocuments(db,collectionName,save)
time_total.stop()
print("Total:{}, load time:{}".format(len(documents),time_total.elapsed))
示例4: LegMotion
class LegMotion(object):
def __init__(self, startValues, endValues, time = 5.0):
self.startValues = startValues
self.endValues = endValues
self.time = time
self.motionTimer = Timer()
self.start()
def start(self):
self.motionTimer.start()
def currentValues(self, dt):
return LegMotion.extrapolateBatch(self.startValues, self.endValues, self.motionTimer.elapsedTime() + dt, self.time)
def isDone(self):
return self.motionTimer.elapsedTime() > self.time
@staticmethod
def extrapolate(startValue, endValue, currentTime, totalTime):
if currentTime > totalTime:
return endValue
return startValue + (endValue - startValue) * (currentTime / totalTime)
@staticmethod
def extrapolateBatch(startValues, endValues, currentTime, totalTime):
if len(startValues) != len(endValues):
print("Error: startValues and endValues must have the same length in LegMotion.extrapolateBatch()")
res = []
for i in range(len(startValues)):
res.append(LegMotion.extrapolate(startValues[i], endValues[i], currentTime, totalTime))
return res
示例5: test_call_repeatedly
def test_call_repeatedly(self):
t = Timer()
try:
t.schedule.enter_after = Mock()
myfun = Mock()
myfun.__name__ = bytes_if_py2("myfun")
t.call_repeatedly(0.03, myfun)
self.assertEqual(t.schedule.enter_after.call_count, 1)
args1, _ = t.schedule.enter_after.call_args_list[0]
sec1, tref1, _ = args1
self.assertEqual(sec1, 0.03)
tref1()
self.assertEqual(t.schedule.enter_after.call_count, 2)
args2, _ = t.schedule.enter_after.call_args_list[1]
sec2, tref2, _ = args2
self.assertEqual(sec2, 0.03)
tref2.canceled = True
tref2()
self.assertEqual(t.schedule.enter_after.call_count, 2)
finally:
t.stop()
示例6: toStart
def toStart(message, controller):
if message is not "":
global TIMEVAR
controller.show_frame(StartGame)
global USERNAME
USERNAME = message
Timer.startTimer(SCORE,TIMEVAR)
示例7: test_enter_after
def test_enter_after(self):
t = Timer()
t._enter = Mock()
fun = Mock(name='fun')
time = Mock(name='time')
time.return_value = 10
t.enter_after(10, fun, time=time)
time.assert_called_with()
t._enter.assert_called_with(20, 0, fun)
示例8: test_supports_Timer_interface
def test_supports_Timer_interface(self):
x = Timer()
x.stop()
tref = Mock()
x.cancel(tref)
tref.cancel.assert_called_with()
assert x.schedule is x
示例9: __mainLoop
def __mainLoop(self):
while not self.done:
Timer.tick()
self.sprites.update()
self.particles.update()
while self.paused: self.__gameInput()
self.__gameInput()
self.collider.DetectCollisions()
self.__updateGame()
self.__drawScene()
示例10: Transition
class Transition(PubSub):
def __init__(self, current, next):
PubSub.__init__(self)
self.current = current
self.next = next
self.timer = Timer()
self.timer.on('tick', self.on_timer)
self.timer.on('finished', self.on_timer_finished)
self.timer.on('started', self.on_timer_started)
self.parent_temp = None
def start(self, delay=0, duration='infinite', interval=0, repeats='infinite', message_type='tick'):
if self.current.parent == None or self.current == self.next:
return
if self.current.transitioning or self.next.transitioning:
print 'stopping'
return
self.emitter = self.current._stage
self.timer.start(self.emitter, delay, duration, interval, repeats, message_type)
def on_timer_started(self):
self.current.transitioning = True
self.next.transitioning = True
self.next.transition_target = [self.current.x, self.current.y, self.next.width, self.next.height]
self.on_start()
self.emit('started')
self.parent_temp = self.next.parent
self.current.parent.add_child(self.next)
if self.current.parent.on_stage:
self.next.enter(self.current)
def on_start(self):
pass
def on_timer(self):
pass
def on_stop(self):
pass
def on_timer_finished(self, event, **kwargs):
self.emit('finished', event = event, args = kwargs)
self.current.parent.remove_child(self.current)
self.current.transitioning = False
self.next.transitioning = False
self.next.transition_target = None
if self.parent_temp is not None:
self.parent_temp.add_child(self.current)
self.current.exit(self.next)
self.on_stop()
示例11: __init__
def __init__(self, current, next):
PubSub.__init__(self)
self.current = current
self.next = next
self.timer = Timer()
self.timer.on('tick', self.on_timer)
self.timer.on('finished', self.on_timer_finished)
self.timer.on('started', self.on_timer_started)
self.parent_temp = None
示例12: __init__
def __init__(self,parent=None,debug=True):
super(cMainFrame,self).__init__(parent)
self.debug=debug
# Gestion des paramêtres projet
self.oProjetIMD=Projet.ProjetIMD(self)
# Initialiser les différents Timer
self.oTimer=Timer.cTimer(self)
# Gestion des fonctions de l'IHM, module Notebook
self.oNoteBook=NoteBook.NoteBook(self)
# Gestion des fonctions de l'IHM, module Notebook
self.oPlastProcess=PlastProcess.PlastProcess(self)
#Initialisation des éléments IHM
self.m_statusBar.SetStatusWidths([250,-1])
if (self.oNoteBook.RefreshOnListBox_vtk(self.oProjetIMD.projet["root"]["dir"]["plast3d"])==-1):
print >>sys.stderr,"Erreur: Répertoire ""plast"" de base non présent sous le dossier IMD3D."
else:
self.oTimer.oRefreshListeofVTKTimer.Start(10000)
#Init Visualisation 3D-vtk du cache des points et cell_data
self.cache_liste_points={}
self.m_choice_vtk_color.Clear()
self.m_choice_vtk_color.Append("Z-Hauteur")
self.m_choice_vtk_color.SetSelection(0)
##début du test pour chargé un STL et le transformer en BMP 2D####
# a=pystl.cSTL("./stl/ship.stl")
# a.read(scale=500,fileformat='b')
# _size,_buffer=a.raw_bitmap()
# image_bmp = Common.scale_bitmap(wx.BitmapFromBuffer(_size[0],_size[1],_buffer),500,500)
# self.TopLevelParent.m_bitmap_test.SetBitmap(image_bmp)
##fin du test
#Init du directory PLAST3D-VTK (certaines propriétés IHM de la Class DirPicker ne sont pas settable via wxFormBuilder
self.m_dirPicker_PLAST3D.SetPath(self.oProjetIMD.projet["root"]["dir"]["plast3d"])
self.m_dirPicker_PLAST3D.GetPickerCtrl().SetLabel("Répertoire de l'éxécutable PLAST.EXE")
#il est impossible de modifier le control text en READ_ONLY après sa création => self.m_dirPicker_PLAST3D.GetTextCtrl().SetDefaultStyle(wx.TE_READONLY)
#On opte pour attacher l'événement KILL_FOCUS et SET_FOCUS afi de vérifier si le directory entré "à la main" est juste
self.m_dirPicker_PLAST3D.GetTextCtrl().Bind( wx.EVT_KILL_FOCUS, self.OnKillFocus_DIR_PLAST3D )
self.m_dirPicker_PLAST3D.GetTextCtrl().Bind( wx.EVT_SET_FOCUS, self.OnSetFocus_DIR_PLAST3D )
#Message dans la console
self.m_textCtrl_console.AppendText("(c) Dynamic3D/Python4D - 01/2013 - Version %s\n"%__version__)
self.m_textCtrl_console.AppendText("OpenGL, version utilisée:%s\n" % self.oVueOpenGL.OpenGlVersion.split('-')[0])
if self.debug==True:
self.m_textCtrl_console.SetDefaultStyle(wx.TextAttr(wx.RED))
self.m_textCtrl_console.AppendText("(!!!Attention vous êtes en MODE Debug les chargements des fichiers et animations ne sont pas optimisés !!!)\n")
self.m_textCtrl_console.SetDefaultStyle(wx.TextAttr(wx.BLACK))
self.m_textCtrl_console.AppendText("Bienvenue sur l'interface OpenGL/Python du projet IMD3D\n")
if self.debug==True:
sys.stdout = Common.RedirectOutput("out",self.m_textCtrl_console)
sys.stderr = Common.RedirectOutput("err",self.m_textCtrl_console)
self.Maximize()
self.Show()
wx.SplashScreen(wx.Bitmap("./images/splash.png"), wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,2000, None, -1,style=wx.BORDER_NONE).Show()
示例13: run
def run(self, export_lim, import_lim, total_delay_time=750):
print "Estimating total entries to import...",
no_of_entries = self.es_conn.search(index=self.es_index,
doc_type='jobTitle',
body=self.es_query,
size=1)['hits']['total']
print "%d entries" % no_of_entries
print "Begin to import..."
exported = 0
start = 0
while start <= no_of_entries and (self.hard_lim_export == 0 or start <= self.hard_lim_export):
exported_entries = self.es_export_rows(start, export_lim)
exported += len(exported_entries)
start += export_lim
sys.stdout.write("\r Exported %d entries of total %d entries..." % (exported, no_of_entries))
sys.stdout.flush()
delay_timer = Timer()
self.insert_sqlite(exported_entries, import_lim)
delay_timer.sleep_if_not_enough(total_delay_time)
示例14: run
def run(self, timeout=None):
if timeout:
Timer.addTimer(timeout, self.stop)
while True:
try:
if self.profileFlag == 0:
self.asyncLoop()
else:
if self.profile is None:
self.createProfile()
self.profile.runcall(self.asyncLoop)
except KeyboardInterrupt:
break
except:
# ignore all exceptions
pass
if self.stoped:
break
asio.closeAll()
asio.loop(0.05, True, self.socketMap)
示例15: test_handle_error
def test_handle_error(self):
from datetime import datetime
on_error = Mock(name='on_error')
s = Timer(on_error=on_error)
with patch('kombu.async.timer.to_timestamp') as tot:
tot.side_effect = OverflowError()
s.enter_at(Entry(lambda: None, (), {}),
eta=datetime.now())
s.enter_at(Entry(lambda: None, (), {}), eta=None)
s.on_error = None
with pytest.raises(OverflowError):
s.enter_at(Entry(lambda: None, (), {}),
eta=datetime.now())
on_error.assert_called_once()
exc = on_error.call_args[0][0]
assert isinstance(exc, OverflowError)