def main(): screen.fill(background) if "MPD_HOST" not in os.environ: print "No MPD_HOST var defined" exit() mpc_player = mpc.Mpc(os.environ["MPD_HOST"]) gpio.GpioMonitor(gpio.BUTTON_RIGHT, backlight.switch_backlight_off) gpio.GpioMonitor(gpio.BUTTON_RIGHT_MIDDLE, mpc_player.song_next) gpio.GpioMonitor(gpio.BUTTON_LEFT_MIDDLE, mpc_player.song_previous) control_bar = pygame.sprite.RenderPlain( controlbar.DisplaySongPrevious(mpc_player), controlbar.DisplaySongNext(mpc_player), controlbar.DisplayPlayerStop(mpc_player), controlbar.DisplayPlayerToggle(mpc_player), ) volume_bar = pygame.sprite.RenderPlain( volumebar.DisplayVolumeDown(mpc_player), volumebar.DisplayVolumeMute(mpc_player), volumebar.DisplayVolumeUp(mpc_player), ) all_clickable = pygame.sprite.Group() all_clickable.add(control_bar) all_clickable.add(volume_bar) track_info = pygame.sprite.RenderPlain( trackinfo.DisplayPlayerTrack(mpc_player), trackinfo.DisplayPlayerProgress(mpc_player) ) timer.set_timer() clock = pygame.time.Clock() running = 1 mpc_player.refresh_volume() mpc_player.refresh_play_status() mpc_player.refresh_current_song() mpc_player.refresh_time() mpc_player.enable_idle() while running: for event in pygame.event.get(): if timer.is_timer(event.type): switch_backlight_off() if event.type == pygame.MOUSEBUTTONDOWN: on_touch(all_clickable) if event.type == pygame.QUIT: running = 0 track_info.draw(screen) control_bar.draw(screen) volume_bar.draw(screen) pygame.display.flip() clock.tick(20)
def _IPKernelApp_start(self): if self.poller is not None: self.poller.start() self.kernel.start() # set up a timer to periodically poll the zmq ioloop loop = ioloop.IOLoop.instance() def poll_ioloop(timer_id, time): global _kernel_running # if the kernel has been closed then run the event loop until it gets to the # stop event added by IPKernelApp.shutdown_request if self.kernel.shell.exit_now: _log.debug("IPython kernel stopping (%s)" % self.connection_file) timer.kill_timer(timer_id) loop.start() _kernel_running = False return # otherwise call the event loop but stop immediately if there are no pending events loop.add_timeout(0, lambda: loop.add_callback(loop.stop)) loop.start() global _kernel_running _kernel_running = True timer.set_timer(100, poll_ioloop)
def get_qt_app(): """ returns the global QtGui.QApplication instance and starts the event loop if necessary. """ app = QtCore.QCoreApplication.instance() if app is None: # create a new application app = QtGui.QApplication([]) # use timer to process events periodically processing_events = {} def qt_timer_callback(timer_id, time): if timer_id in processing_events: return processing_events[timer_id] = True try: app = QtCore.QCoreApplication.instance() if app is not None: app.processEvents(QtCore.QEventLoop.AllEvents, 300) finally: del processing_events[timer_id] timer.set_timer(100, qt_timer_callback) return app
def on_touch(all_clickable): timer.set_timer() if backlight.is_screensaver_enabled(): backlight.switch_backlight_on() return mouse_rect = pygame.sprite.Sprite() mouse_rect.rect = pygame.Rect(pygame.mouse.get_pos(), (1, 1)) imagehit = pygame.sprite.spritecollideany(mouse_rect, all_clickable, False) if imagehit: imagehit.run_callback()
def __init__ (self, delay=1000, max=10): self.x = 0 self.max = max self.id = timer.set_timer (delay, self.increment) # Could use the threading module, but this is # a win32 extension test after all! :-) self.event = win32event.CreateEvent(None, 0, 0, None)
def OnTimer(self, id, timeVal): if id: timer.kill_timer (id) if self.intervaler.IsTime() or self.bConnectNow : # do the work. try: self.dlg.SetWindowText(self.dlg.title + " - Working...") self.dlg.butOK.EnableWindow(0) self.dlg.butCancel.EnableWindow(0) self.CaptureOutput() try: exec(self.dlg.doWork) print "The last operation completed successfully." except: t, v, tb = sys.exc_info() str = "Failed: %s: %s" % (t, `v`) print str self.oldErr.write(str) tb = None # Prevent cycle finally: self.ReleaseOutput() self.dlg.butOK.EnableWindow() self.dlg.butCancel.EnableWindow() self.dlg.SetWindowText(self.dlg.title) else: now = time.time() nextTime = self.intervaler.GetNextTime() if nextTime: timeDiffSeconds = nextTime - now timeDiffMinutes = int(timeDiffSeconds / 60) timeDiffSeconds = timeDiffSeconds % 60 timeDiffHours = int(timeDiffMinutes / 60) timeDiffMinutes = timeDiffMinutes % 60 self.dlg.prompt1.SetWindowText("Next connection due in %02d:%02d:%02d" % (timeDiffHours,timeDiffMinutes,timeDiffSeconds)) self.timerId = timer.set_timer (self.intervaler.GetWakeupInterval(), self.OnTimer) self.bConnectNow = 0
def __init__(self, app_state, target_url='', icon_path='icon.ico'): self.app_state = app_state self.target_url = target_url self.message_id = win32con.WM_USER+20 self.window_id = self.create_window() # load the icon self.icon = win32gui.LoadImage( None, icon_path, win32con.IMAGE_ICON, 0, 0, win32con.LR_LOADFROMFILE ) # set tray icon properties self.notify_id = ( self.window_id, 0, win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP, self.message_id, self.icon, # NOTE: This is a comment about `GeoBox` self.app_state.gettext('GeoBox'), ) win32gui.Shell_NotifyIcon( win32gui.NIM_ADD, self.notify_id ) log.debug('Tray icon attached') self.timer_id = timer.set_timer(1000, self.check_for_shutdown)
def _DoStartNotifyTimer(self, delay): assert thread.get_ident() == self.owner_thread_ident assert self.notify_timer_id is None, "Shouldn't start a timer when already have one" assert isinstance(delay, types.FloatType), "Timer values are float seconds" assert delay, "No delay means no timer!" delay = int(delay*1000) # convert to ms. self.notify_timer_id = timer.set_timer(delay, self._NotifyTimerFunc) self.LogDebug(1, "Notify timer started - id=%d, delay=%d" % (self.notify_timer_id, delay))
def _UpdateStatus(self): # We have problems with the order of events - we get the notification # events before the new states are available via GetItem. # Therefore, we start a one-shot, immediate timer, which ends up # at the end of the message queue, and we work. import timer if self.timer_id is not None: timer.kill_timer(self.timer_id) self.timer_id = timer.set_timer (0, self._DoUpdateStatus)
def Init(self): processors.ButtonProcessor.Init(self) self.back_btn_hwnd = self.GetControl(self.back_btn_id) self.forward_btn_hwnd = self.GetControl() self.forward_captions = win32gui.GetWindowText(self.forward_btn_hwnd).split(",") self.page_placeholder_hwnd = self.GetControl(self.page_placeholder_id) self.page_stack = [] self.switchToPage(0) self.timer_id = timer.set_timer(800, self.OnCheckForwardTimer)
def Create(self, title, style, rect, parent): classStyle = win32con.CS_HREDRAW | win32con.CS_VREDRAW className = win32ui.RegisterWndClass(classStyle, 0, win32con.COLOR_WINDOW+1, 0) self._obj_ = win32ui.CreateWnd() self._obj_.AttachObject(self) self._obj_.CreateWindow(className, title, style, rect, parent, win32ui.AFX_IDW_PANE_FIRST) self.HookMessage (self.OnSize, win32con.WM_SIZE) self.HookMessage (self.OnPrepareToClose, WM_USER_PREPARE_TO_CLOSE) self.HookMessage (self.OnDestroy, win32con.WM_DESTROY) self.timerid = timer.set_timer (100, self.OnTimer) self.InvalidateRect()
def notify(self, hwnd, msg, wparam, lparam): # Double click is actually 1 single click followed # by a double-click event, no way to differentiate # So we need a timed callback to cancel if lparam == win32con.WM_LBUTTONDBLCLK: self.execute_menu_option(self.default_menu_index + self.FIRST_ID) self.stop_click_timer() elif lparam == win32con.WM_RBUTTONUP: self.show_menu() elif lparam == win32con.WM_LBUTTONDOWN: # Wrapper of win32api, timeout is in ms # We need to wait at least untill what user has defined as double click self.stop_click_timer() self.click_timer = timer.set_timer(win32gui.GetDoubleClickTime(), self.click) return True
def kbEvent(self, nCode, wParam, lParam): if nCode >= 0: # It just occured to me that I should aso be checking for WM_SYSKEYDOWN as well if wParam is win32con.WM_KEYDOWN: if not self.pending and lParam[0] == 0xBA and not mods(): if self.presscount >= 0: if self.timer_id is None: self.timer_id = timer.set_timer(self.delay, self.timer_fn) self.presscount += 1 if self.presscount > 0: # return a non-zero to prevent further processing return 42 else: self.go() return windll.user32.CallNextHookEx(self.keyboardHook.kbHook, nCode, wParam, lParam)
def _start_timer(timeout=300, interval=0.1): """ Creates and starts a timer function that adds any registered shortcuts to Excel. As the COM object needed to do that may not exist at startup this function retries a number of times. """ global _timer_id def make_timer_func(): start_time = time.time() def on_timer(timer_id, unused): # when Excel is starting up and PyXLL imports its modules there # is no Excel window, and so the COM object needed to register # the shortcut might not be available yet. try: xl_window = get_active_object() except RuntimeError: if time.time() - start_time > timeout: _log.error("Timed out waiting for Excel COM interface to become available.") timer.kill_timer(timer_id) _timer_id = None return # Get the Excel application from its window xl_app = Dispatch(xl_window).Application while _shortcuts_to_add: accelerator, macroname = _shortcuts_to_add.pop() try: xl_app.OnKey(accelerator, macroname) except: _log.error("Failed to add shortcut %s -> %s" % (accelerator, macroname), exc_info=True) _log.debug("Finished adding shortcuts") timer.kill_timer(timer_id) _timer_id = None return on_timer # start the timer _timer_id = timer.set_timer(int(interval * 1000), make_timer_func())
def main(): menu_options = ( ('Open Dashboard', None, open_dashboard), ('Check for updates', None, check_updates),) #('Start Service', None, start_service),) #('Stop Service', None, stop_service), #('Reset Password', None, reset_password)) icon = "icons/mycubevaulticon.ico" hover_text = 'MyCube Vault' st = SysTray(icon, hover_text, menu_options, on_quit=quit_services, default_menu_index=1) start_service(st) import timer def callback(timer_id, timer_t): try: data = urllib2.urlopen("http://%s:%s/check_restart" % (HOST, st.server_port), timeout=2).read() if data == "true": restart_service(st) except Exception: pass def update_monitor(timer_id, timer_t): if need_update(): if not (hasattr(st, 'displayed') and st.displayed): with_update_dialog(st) else: timer.kill_timer(timer_id) def update_on_start(timer_id, timer_t): print "startup update" timer.kill_timer(timer_id) if need_update(): with_update_dialog(st) timer.set_timer(3000, callback) timer.set_timer(3600 * 1000, update_monitor) timer.set_timer(10 * 1000, update_on_start) st.run()
def Init(self): self.busy = 0 self.wAngleY = 10.0 self.wAngleX = 1.0 self.wAngleZ = 5.0 self.timerid = timer.set_timer (150, self.OnTimer)
def Init(self): self.busy = 0 self.wAngleY = 10.0 self.wAngleX = 1.0 self.wAngleZ = 5.0 self.timerid = timer.set_timer(150, self.OnTimer)
def hc_plot(chart, control_name, theme=None): """ This function is used by the other plotting functions to render the chart as html and display it in Excel. """ # add the theme if there is one if theme: chart.add_JSsource(["https://code.highcharts.com/themes/%s.js" % theme]) # get the calling sheet caller = xlfCaller() sheet_name = caller.sheet_name # split into workbook and sheet name match = re.match("^\[(.+?)\](.*)$", sheet_name.strip("'\"")) if not match: raise Exception("Unexpected sheet name '%s'" % sheet_name) workbook, sheet = match.groups() # get the Worksheet object xl = xl_app() workbook = xl.Workbooks(workbook) sheet = workbook.Sheets(sheet) # find the existing webbrowser control, or create a new one try: control = sheet.OLEObjects(control_name[:31]) browser = control.Object except: control = sheet.OLEObjects().Add(ClassType="Shell.Explorer.2", Left=147, Top=60.75, Width=400, Height=400) control.Name = control_name[:31] browser = control.Object # set the chart aspect ratio to match the browser if control.Width > control.Height: chart.set_options("chart", { "height": "%d%%" % (100. * control.Height / control.Width) }) else: chart.set_options("chart", { "width": "%d%%" % (100. * control.Width / control.Height) }) # get the html and add the 'X-UA-Compatible' meta-tag soup = BeautifulSoup(chart.htmlcontent) metatag = soup.new_tag("meta") metatag.attrs["http-equiv"] = "X-UA-Compatible" metatag.attrs['content'] = "IE=edge" soup.head.insert(0, metatag) # write out the html for the browser to render fh = tempfile.NamedTemporaryFile("wt", suffix=".html", delete=False) filename = fh.name # clean up the file after 10 seconds to give the browser time to load def on_timer(timer_id, time): timer.kill_timer(timer_id) os.unlink(filename) timer.set_timer(10000, on_timer) fh.write(soup.prettify()) fh.close() # navigate to the temporary file browser.Navigate("file://%s" % filename) return "[%s]" % control_name
def _UpdateStatus(self): import timer if self.timer_id is not None: timer.kill_timer(self.timer_id) self.timer_id = timer.set_timer (0, self._DoUpdateStatus)
def _start_kernel(): """starts the ipython kernel and returns the ipython app""" from IPython.zmq.ipkernel import IPKernelApp from zmq.eventloop import ioloop global _kernel_running, _ipython_app if _kernel_running: return _ipython_app # get the app if it exists, or set it up if it doesn't if IPKernelApp.initialized(): app = IPKernelApp.instance() else: app = IPKernelApp.instance() app.initialize() # Undo unnecessary sys module mangling from init_sys_modules. # This would not be necessary if we could prevent it # in the first place by using a different InteractiveShell # subclass, as in the regular embed case. main = app.kernel.shell._orig_sys_modules_main_mod if main is not None: sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main app.kernel.user_module = sys.modules[__name__] app.kernel.user_ns = {} # patch in auto-completion support # added in https://github.com/ipython/ipython/commit/f4be28f06c2b23cd8e4a3653b9e84bde593e4c86 # we effectively make the same patches via monkeypatching from IPython.core.interactiveshell import InteractiveShell old_set_completer_frame = InteractiveShell.set_completer_frame # restore old set_completer_frame that gets no-op'd out in ZmqInteractiveShell.__init__ bound_scf = old_set_completer_frame.__get__(app.shell, InteractiveShell) app.shell.set_completer_frame = bound_scf app.shell.set_completer_frame() # start the kernel app.kernel.start() # set up a timer to periodically poll the zmq ioloop loop = ioloop.IOLoop.instance() def poll_ioloop(timer_id, time): global _kernel_running # if the kernel has been closed then run the event loop until it gets to the # stop event added by IPKernelApp.shutdown_request if app.kernel.shell.exit_now: _log.debug("IPython kernel stopping (%s)" % app.connection_file) timer.kill_timer(timer_id) ioloop.IOLoop.instance().start() _kernel_running = False return # otherwise call the event loop but stop immediately if there are no pending events loop.add_timeout(0, lambda: loop.add_callback(loop.stop)) ioloop.IOLoop.instance().start() _log.debug("IPython kernel starting. Use '--existing %s' to connect." % app.connection_file) timer.set_timer(100, poll_ioloop) _kernel_running = True _ipython_app = app return _ipython_app
def _run(self): timer.set_timer(100, self._timer_func) # while not win32gui.PumpWaitingMessages(): # self.process_idle_tasks() # time.sleep(0.1) win32gui.PumpMessages()
# Выведем информацию. print можно написать по разному. # Здесь вначале создадим строку 'my_callback {} time={}' в которую с помощью # format подставим два значения на место значков {} # format - функция присущая текстовым строкам # получившуюся после подстановки значений строку отправим print-у print('my_callback {} time={}'.format(timer_id, time)) # В выводе можем заметить, что все выведенные time отличаются почти на 100 global my_timer_id # Явно показываем, что берём глобальную переменную print('my_timer_id == timer_id {}'.format(my_timer_id == timer_id)) # как мы увидим, идентификаторы имеют одинаковое значение. global counter # Явно показываем, что берём глобальную переменную, # вдруг новую локальную создаст, или упадёт counter = counter + 1 # После 4-го срабатывания остановим таймер и удалим из ОС if counter == 4: # Останавливаем таймер. timer.kill_timer(timer_id) # Создадим таймер, с интервалом и функцией обратного вызова. # Сам таймер создастся где-то в недрах ОС, мы получим только его идентификатор (номер) в my_timer_id my_timer_id = timer.set_timer(my_millisecundes_interval, my_callback) # И сразу после создания пошли выполняться дальше if my_timer_id == 0: print('Не удалось создать тааймер!') print(type(my_timer_id)) # Нужно обязательно остановить таймер, иначе он останется работать. # Здесь мы этого сделать не можем: сюда мы проскочим ещё # до первого вызова my_callback и вессь смысл потеряется # Поэтому нужно либо писать сложную обёртку (в большой сложной программе) # или удалять в самом my_callback
def _run(self): timer.set_timer(100, self._timer_func) win32gui.PumpMessages()
global time_left global notified global paused if not paused: time_left -= 1 if time_left <= 0 and not notified: systray.WindowsBalloonTip("Time is up!", "You have 10 minutes to turn off your computer") notified = True save_interval = 60 # Saving interval in seconds if time_left % save_interval == 0: save_time("T", datetime.now()) print(timedelta(seconds=time_left)) sec_timer = timer.set_timer(1000, countdown) def time_change(delta): print(delta.total_seconds()) global time_left time_left += int(delta.total_seconds()) save_time("A", delta) def main_menu(sys_tray_icon): gui.Menu(time_change, timedelta(seconds=time_left)).mainloop() def ondblclick(sys_tray_icon): global paused