Python gi.repository.GLib.timeout_add_seconds() Examples
The following are 28
code examples of gi.repository.GLib.timeout_add_seconds().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
gi.repository.GLib
, or try the search function
.
Example #1
Source File: eventhandler.py From vimiv with MIT License | 6 votes |
def num_append(self, num, remove_by_timeout=True): """Add a new char to num_str. Args: num: The number to append to the string. remove_by_timeout: If True, add a timeout to clear the num_str. """ # Remove old timers if we have new numbers if self._timer_id: GLib.source_remove(self._timer_id) self._timer_id = GLib.timeout_add_seconds(1, self.num_clear) self._num_str += num self._convert_trailing_zeros() # Write number to log file in debug mode if self._app.debug: self._app["log"].write_message("number", num + "->" + self._num_str) self._app["statusbar"].update_info()
Example #2
Source File: windows.py From syncthing-gtk with GNU General Public License v2.0 | 6 votes |
def _peek(self): if self._closed: return False # Check if there is anything to read and read if available (read, nAvail, nMessage) = win32pipe.PeekNamedPipe(self._osfhandle, 0) if nAvail >= self._buffer_size: data = self._pipe.read(self._buffer_size) self._buffer += data # If there is read_async callback and buffer has some data, # send them right away if not self._waits_for_read is None and len(self._buffer) > 0: r = WinPopenReader.Results(self._buffer) self._buffer = "" callback, data = self._waits_for_read self._waits_for_read = None callback(self, r, *data) GLib.idle_add(self._peek) return False GLib.timeout_add_seconds(1, self._peek) return False
Example #3
Source File: timermanager.py From syncthing-gtk with GNU General Public License v2.0 | 6 votes |
def timer(self, name, delay, callback, *data, **kwdata): """ Runs callback after specified number of seconds. Uses GLib.timeout_add_seconds with small wrapping to allow named timers to be canceled by reset() call """ method = GLib.timeout_add_seconds if delay < 1 and delay > 0: method = GLib.timeout_add delay = delay * 1000.0 if name is None: # No wrapping is needed, call GLib directly method(delay, callback, *data, **kwdata) else: if name in self._timers: # Cancel old timer GLib.source_remove(self._timers[name]) # Create new one self._timers[name] = method(delay, self._callback, name, callback, *data, **kwdata)
Example #4
Source File: main.py From PiHole-Panel with GNU General Public License v3.0 | 6 votes |
def __init__(self): Gtk.Window.__init__(self) self.assistant = Gtk.Assistant() grid = Gtk.Grid(margin=4) grid.set_column_homogeneous(True) self.add(grid) self.grid = grid self.status_label, self.status_button = self.draw_status_elements() self.statistics_frame = self.draw_statistics_frame() self.top_queries_frame = self.draw_top_queries_frame() self.top_ads_frame = self.draw_top_ads_frame() self.updates_frame = self.draw_updates_frame() self.header_bar = self.draw_header_bar() self.hosts_combo = self.draw_hosts_combo() # Initial data fetch-and-display self.fetch_data_and_update_display( base_url, web_password) # Create a timer --> self.on_timer will be called periodically glib.timeout_add_seconds(update_interval_seconds, self.on_timer)
Example #5
Source File: alttoolbar_sidebar.py From alternative-toolbar with GNU General Public License v3.0 | 6 votes |
def edit_playlist(self, leaf_iter): """ edit the playlist :param leaf_iter: treestore iter :return: """ print("edit_playlist") self.text_renderer.props.editable = True path = self.treestore.get_path(leaf_iter) path = self.treestore_filter.convert_child_path_to_path(path) print(path) self.grab_focus() def delayed(*args): self.set_cursor_on_cell(path, self.tree_column, self.text_renderer, True) GLib.timeout_add_seconds(1, delayed, None)
Example #6
Source File: pomodoro_indicator.py From pomodoro-indicator with GNU General Public License v3.0 | 5 votes |
def start_working_process(self, interval, countdown): if self.pw > 0: GLib.source_remove(self.pw) print('interval', interval) print('pomodoros', self.pomodoros) self.pw = GLib.timeout_add_seconds(interval, countdown)
Example #7
Source File: myweatherindicator.py From my-weather-indicator with MIT License | 5 votes |
def start_looking_for_internet(self): if self.internet_updater > 0: GLib.source_remove(self.internet_updater) if self.looking_for_internet(): self.internet_updater = GLib.timeout_add_seconds( TIME_TO_CHECK, self.looking_for_internet)
Example #8
Source File: myweatherindicator.py From my-weather-indicator with MIT License | 5 votes |
def start_weather_updater(self): if self.weather_updater > 0: GLib.source_remove(self.weather_updater) self.update_weather() self.weather_updater = GLib.timeout_add_seconds(self.refresh * 3600, self.update_weather)
Example #9
Source File: error.py From coinprice-indicator with MIT License | 5 votes |
def is_ok(self): max = self.count <= MAX_ERRORS if (max is False): self.log("Error limit reached. Cooling down for " + str(REFRESH_INTERVAL) + " seconds.") self.exchange.stop() GLib.timeout_add_seconds(REFRESH_INTERVAL, self.exchange.restart) self.chill = True else: self.chill = False return max
Example #10
Source File: exchange.py From coinprice-indicator with MIT License | 5 votes |
def start(self, error_refresh=None): if not self.started: self._check_price() self.started = True refresh = error_refresh if error_refresh else self.indicator.refresh_frequency self.timeout_id = GLib.timeout_add_seconds(refresh, self._check_price) return self ## # Stop exchange, reset errors #
Example #11
Source File: cpug.py From cpu-g with GNU General Public License v3.0 | 5 votes |
def start_battery_updater(self): if self.battery_updater > 0: GLib.source_remove(self.battery_updater) if self.exists_battery is True: self.get_battery_duration() self.battery_updater = GLib.timeout_add_seconds( 300, self.get_battery_duration)
Example #12
Source File: cpug.py From cpu-g with GNU General Public License v3.0 | 5 votes |
def start_uptime_update(self): if self.uptime_updater > 0: GLib.source_remove(self.uptime_updater) self.uptime_update() self.uptime_updater = GLib.timeout_add_seconds(60, self.uptime_update)
Example #13
Source File: cpug.py From cpu-g with GNU General Public License v3.0 | 5 votes |
def start_ram_updater(self): if self.ram_updater > 0: GLib.source_remove(self.ram_updater) self.ram_update() self.ram_updater = GLib.timeout_add_seconds(1, self.ram_update)
Example #14
Source File: FlatCAMObj.py From FlatCAM with MIT License | 5 votes |
def on_generatecnc_button_click(self, *args): self.read_form() job_name = self.options["name"] + "_cnc" # Object initialization function for app.new_object() # RUNNING ON SEPARATE THREAD! def job_init(job_obj, app_obj): assert isinstance(job_obj, FlatCAMCNCjob) # Propagate options job_obj.options["tooldia"] = self.options["cnctooldia"] GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job...")) job_obj.z_cut = self.options["cutz"] job_obj.z_move = self.options["travelz"] job_obj.feedrate = self.options["feedrate"] GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry...")) # TODO: The tolerance should not be hard coded. Just for testing. job_obj.generate_from_geometry(self, tolerance=0.0005) GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code...")) job_obj.gcode_parse() # TODO: job_obj.create_geometry creates stuff that is not used. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry...")) #job_obj.create_geometry() GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting...")) # To be run in separate thread def job_thread(app_obj): app_obj.new_object("cncjob", job_name, job_init) GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name)) GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!")) GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, "Idle")) # Send to worker self.app.worker.add_task(job_thread, [self.app])
Example #15
Source File: FlatCAMObj.py From FlatCAM with MIT License | 5 votes |
def on_create_cncjob_button_click(self, *args): self.read_form() job_name = self.options["name"] + "_cnc" # Object initialization function for app.new_object() def job_init(job_obj, app_obj): assert isinstance(job_obj, FlatCAMCNCjob) GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job...")) job_obj.z_cut = self.options["drillz"] job_obj.z_move = self.options["travelz"] job_obj.feedrate = self.options["feedrate"] # There could be more than one drill size... # job_obj.tooldia = # TODO: duplicate variable! # job_obj.options["tooldia"] = job_obj.generate_from_excellon_by_tool(self, self.options["toolselection"]) GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code...")) job_obj.gcode_parse() GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry...")) job_obj.create_geometry() GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting...")) # To be run in separate thread def job_thread(app_obj): app_obj.new_object("cncjob", job_name, job_init) GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!")) GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, "")) # Send to worker self.app.worker.add_task(job_thread, [self.app])
Example #16
Source File: sniffer.py From btle-sniffer with MIT License | 5 votes |
def run(self): """ Run the Sniffer main loop. """ if self.adapter is not None: self._log.debug("Clearing the BlueZ device registry.") for path, _ in get_known_devices(): self.adapter.RemoveDevice(path) self._log.debug("Registering the signals InterfacesAdded and PropertiesChanged.") bus = pydbus.SystemBus() bus.subscribe( sender=SERVICE_NAME, iface=OBJECT_MANAGER_INTERFACE, signal="InterfacesAdded", signal_fired=self._cb_interfaces_added ) bus.subscribe( sender=SERVICE_NAME, iface=OBJECT_MANAGER_INTERFACE, signal="InterfacesRemoved", signal_fired=self._cb_interfaces_removed ) bus.subscribe( sender=SERVICE_NAME, iface=PROPERTIES_INTERFACE, signal="PropertiesChanged", arg0=DEVICE_INTERFACE, signal_fired=self._cb_properties_changed ) self._log.debug("Running the main loop.") if self.output_path is not None and self.backup_interval > 0: GLib.timeout_add_seconds(self.backup_interval, self._cb_backup_registry) if self.attempt_connection: GLib.timeout_add_seconds(self.queueing_interval, self._cb_connect_check) loop = GLib.MainLoop() loop.run() else: raise ValueError("Sniffer.run can only be called in a context " "(e.g. `with Sniffer(...) as s: s.run()`)")
Example #17
Source File: alttoolbar_sidebar.py From alternative-toolbar with GNU General Public License v3.0 | 5 votes |
def _row_click(self, widget, event): """ event called when clicking on a row """ print('_row_click') try: treepath, treecolumn, cellx, celly = \ widget.get_path_at_pos(event.x, event.y) except: print("exit") return active_object = self.treestore_filter[treepath][1] print(active_object) if active_object: # we have a source self._user_clicked = True self.shell.props.display_page_tree.select(active_object) self.rbtree.expand_all() if self._last_click_source == active_object: self.text_renderer.props.editable = \ "PlaylistSource" in type(active_object).__name__ else: self.text_renderer.props.editable = False self._last_click_source = active_object def delayed(*args): # save current state of each category in the treeview cat_vals = {} for category in self._category: path = self.treestore.get_path(self._category[category]) if path: cat_vals[category] = self.row_expanded(path) self.expanders = str(cat_vals) print(self.expanders) GLib.timeout_add_seconds(1, delayed)
Example #18
Source File: widgets.py From badKarma with GNU General Public License v3.0 | 5 votes |
def __init__(self, url, proxy=False, *args, **kwargs): super(WebView, self).__init__(*args, **kwargs) """ WebKit2 Webview widget """ web_context = WebKit2.WebContext.get_default() web_context.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE) if proxy: # proxy False or "http://127.0.0.1:8080" web_context.set_network_proxy_settings(WebKit2.NetworkProxyMode.CUSTOM, WebKit2.NetworkProxySettings.new(proxy)) self.set_hexpand(True) self.set_vexpand(True) self.toolbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) self.address_bar = Gtk.Entry() self.go_button = Gtk.Button("go") self.address_bar.set_text(url) self.toolbar.add(self.address_bar) self.toolbar.add(self.go_button) if proxy: GLib.timeout_add_seconds(2, self._reload) self.toolbar.set_hexpand(True) self.address_bar.set_hexpand(True) self.load_uri(url) self.toolbar.show_all() self.show_all() self.load_uri(url) self.connect("load-changed", self._load_changed) self.go_button.connect("clicked", self._load_uri)
Example #19
Source File: blunders.py From pychess with GNU General Public License v3.0 | 5 votes |
def start(discoverer): atexit.register(SubProcess.finishAllSubprocesses) pgnfile, gameno = queryGameno(sys.argv[1]) analyzer = queryAnalyzer(discoverer.getAnalyzers()) secs = queryTime() name1, name2 = pgnfile.get_player_names(gameno) print("%s will now analyze the game between %s and %s with %d seconds per move." % \ (discoverer.getName(analyzer), name1, name2, secs)) print() global game, values values = {} game = GameModel() game.setPlayers([DummyPlayer(), DummyPlayer()]) analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant) analyzer.connect('analyze', onAnalyze) game.spectators[HINT] = analyzer game.loadAndStart(sys.argv[1], pgn, gameno, -1) def cb(): if game.ply == game.lowply: on_finish() return False check_blund() return True GLib.timeout_add_seconds(secs, cb)
Example #20
Source File: player.py From Audio-Cutter with GNU General Public License v3.0 | 5 votes |
def play(self, *args): """Play the current audio file.""" def on_duration_changed(): self.emit("duration-changed") return self.is_playing if self.is_playing: # Stop the current audio file from playing self.stop() self._playbin.set_state(Gst.State.PLAYING) self.is_playing = True self.emit("playing") GLib.timeout_add_seconds(1, on_duration_changed)
Example #21
Source File: sensors.py From indicator-sysmonitor with GNU General Public License v3.0 | 5 votes |
def __init__(self, parent): Thread.__init__(self) self._parent = parent self.mgr = SensorManager() self.alive = Event() self.alive.set() GLib.timeout_add_seconds(self.mgr.get_interval(), self.run)
Example #22
Source File: network.py From mopidy-mpd with Apache License 2.0 | 5 votes |
def enable_timeout(self): """Reactivate timeout mechanism.""" if self.timeout is None or self.timeout <= 0: return self.disable_timeout() self.timeout_id = GLib.timeout_add_seconds( self.timeout, self.timeout_callback )
Example #23
Source File: campaign.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, *args, **kwargs): super(CampaignViewDashboardTab, self).__init__(*args, **kwargs) self.graphs = [] """The :py:class:`.CampaignGraph` classes represented on the dash board.""" dash_ports = { # dashboard position, (width, height) 'top_left': (380, 200), 'top_right': (380, 200), 'bottom': (760, 200) } for dash_port, details in dash_ports.items(): graph_name = self.config['dashboard.' + dash_port] cls = graphs.get_graph(graph_name) if not cls: self.logger.warning('could not get graph: ' + graph_name) logo_file_path = find.data_file('king-phisher-icon.svg') if logo_file_path: image = Gtk.Image.new_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_size(logo_file_path, 128, 128)) image.show() self.gobjects['scrolledwindow_' + dash_port].add(image) continue graph_inst = cls(self.application, details, getattr(self, self.top_gobject).get_style_context()) self.gobjects['scrolledwindow_' + dash_port].add(graph_inst.canvas) self.gobjects['box_' + dash_port].pack_end(graph_inst.navigation_toolbar, False, False, 0) self.graphs.append(graph_inst) self.logger.debug("dashboard refresh frequency set to {0} seconds".format(self.refresh_frequency)) GLib.timeout_add_seconds(self.refresh_frequency, self.loader_idle_routine)
Example #24
Source File: server_events.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _on_close(self): if self._worker_thread is None: # the socket was never successfully opened return getattr(self.logger, 'warning' if self.reconnect else 'info')('the server event socket has been closed') self._connect_event.clear() if self.__is_shutdown.is_set(): return if self._worker_thread != threading.current_thread(): return self._worker_thread = None if self.reconnect: self._reconnect_event_id = GLib.timeout_add_seconds(30, self._ws_reconnect)
Example #25
Source File: FlatCAMApp.py From FlatCAM with MIT License | 4 votes |
def open_gerber(self, filename): """ Opens a Gerber file, parses it and creates a new object for it in the program. Thread-safe. :param filename: Gerber file filename :type filename: str :return: None """ # Fails here # t = Gtk.TextView() # print t GLib.idle_add(lambda: self.set_progress_bar(0.1, "Opening Gerber ...")) # How the object should be initialized def obj_init(gerber_obj, app_obj): assert isinstance(gerber_obj, FlatCAMGerber) # Opening the file happens here GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ...")) gerber_obj.parse_file(filename) # Further parsing GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Creating Geometry ...")) GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ...")) # Object name name = filename.split('/')[-1].split('\\')[-1] self.new_object("gerber", name, obj_init) # New object creation and file processing # try: # self.new_object("gerber", name, obj_init) # except: # e = sys.exc_info() # print "ERROR:", e[0] # traceback.print_exc() # self.message_dialog("Failed to create Gerber Object", # "Attempting to create a FlatCAM Gerber Object from " + # "Gerber file failed during processing:\n" + # str(e[0]) + " " + str(e[1]), kind="error") # GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "Idle")) # self.collection.delete_active() # return # Register recent file self.register_recent("gerber", filename) # GUI feedback self.info("Opened: " + filename) GLib.idle_add(lambda: self.set_progress_bar(1.0, "Done!")) GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "Idle"))
Example #26
Source File: FlatCAMApp.py From FlatCAM with MIT License | 4 votes |
def open_excellon(self, filename): """ Opens an Excellon file, parses it and creates a new object for it in the program. Thread-safe. :param filename: Excellon file filename :type filename: str :return: None """ GLib.idle_add(lambda: self.set_progress_bar(0.1, "Opening Excellon ...")) # How the object should be initialized def obj_init(excellon_obj, app_obj): GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ...")) excellon_obj.parse_file(filename) excellon_obj.create_geometry() GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ...")) # Object name name = filename.split('/')[-1].split('\\')[-1] # New object creation and file processing try: self.new_object("excellon", name, obj_init) except: e = sys.exc_info() App.log.error(str(e)) self.message_dialog("Failed to create Excellon Object", "Attempting to create a FlatCAM Excellon Object from " + "Excellon file failed during processing:\n" + str(e[0]) + " " + str(e[1]), kind="error") GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "Idle")) self.collection.delete_active() return # Register recent file self.register_recent("excellon", filename) # GUI feedback self.info("Opened: " + filename) GLib.idle_add(lambda: self.set_progress_bar(1.0, "Done!")) GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, ""))
Example #27
Source File: FlatCAMApp.py From FlatCAM with MIT License | 4 votes |
def open_gcode(self, filename): """ Opens a G-gcode file, parses it and creates a new object for it in the program. Thread-safe. :param filename: G-code file filename :type filename: str :return: None """ # How the object should be initialized def obj_init(job_obj, app_obj_): """ :type app_obj_: App """ assert isinstance(app_obj_, App) GLib.idle_add(lambda: app_obj_.set_progress_bar(0.1, "Opening G-Code ...")) f = open(filename) gcode = f.read() f.close() job_obj.gcode = gcode GLib.idle_add(lambda: app_obj_.set_progress_bar(0.2, "Parsing ...")) job_obj.gcode_parse() GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Creating geometry ...")) job_obj.create_geometry() GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Plotting ...")) # Object name name = filename.split('/')[-1].split('\\')[-1] # New object creation and file processing try: self.new_object("cncjob", name, obj_init) except: e = sys.exc_info() App.log.error(str(e)) self.message_dialog("Failed to create CNCJob Object", "Attempting to create a FlatCAM CNCJob Object from " + "G-Code file failed during processing:\n" + str(e[0]) + " " + str(e[1]), kind="error") GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "Idle")) self.collection.delete_active() return # Register recent file self.register_recent("cncjob", filename) # GUI feedback self.info("Opened: " + filename) GLib.idle_add(lambda: self.set_progress_bar(1.0, "Done!")) GLib.timeout_add_seconds(1, lambda: self.set_progress_bar(0.0, "")) ######################################## ## EVENT HANDLERS ## ########################################
Example #28
Source File: daemonprocess.py From syncthing-gtk with GNU General Public License v2.0 | 4 votes |
def start(self): for x in self.env: os.environ[x] = self.env[x] try: self._cancel = Gio.Cancellable() if IS_WINDOWS: # Windows sinfo = STARTUPINFO() sinfo.dwFlags = STARTF_USESHOWWINDOW sinfo.wShowWindow = 0 cflags = nice_to_priority_class(self.priority) self._proc = Popen(self.cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE, startupinfo=sinfo, creationflags=cflags) self._stdout = WinPopenReader(self._proc.stdout) self._check = GLib.timeout_add_seconds(1, self._cb_check_alive) elif HAS_SUBPROCESS: # New Gio flags = Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_MERGE if self.priority == 0: self._proc = Gio.Subprocess.new(self.cmdline, flags) else: # I just really do hope that there is no distro w/out nice command self._proc = Gio.Subprocess.new([ "nice", "-n", "%s" % self.priority ] + self.cmdline, flags) self._proc.wait_check_async(None, self._cb_finished) self._stdout = self._proc.get_stdout_pipe() else: # Gio < 3.12 - Gio.Subprocess is missing :( if self.priority == 0: self._proc = Popen(self.cmdline, stdout=PIPE) else: # still hoping self._proc = Popen([ "nice", "-n", "%s" % self.priority ], stdout=PIPE) self._stdout = Gio.UnixInputStream.new(self._proc.stdout.fileno(), False) self._check = GLib.timeout_add_seconds(1, self._cb_check_alive) except Exception as e: # Startup failed self.emit("failed", e) return self._lines = deque([], DaemonProcess.SCROLLBACK_SIZE) self._buffer = "" self._stdout.read_bytes_async(256, 0, self._cancel, self._cb_read, ())