File: timermanager.py

package info (click to toggle)
syncthing-gtk 0.9.4.4%2Bds%2Bgit20201209%2Bc46fbd8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,260 kB
  • sloc: python: 7,592; sh: 259; xml: 115; makefile: 2
file content (62 lines) | stat: -rw-r--r-- 1,601 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""
Syncthing-GTK - Timer manager

Simple abstract class for named, cancelable timers
"""


from gi.repository import GLib

class TimerManager(object):
	def __init__(self):
		self._timers = {}
	
	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)
	
	def timer_active(self, name):
		""" Returns True if named timer is active """
		return (name in self._timers)
	
	def cancel_timer(self, name):
		"""
		Cancels named timer. Returns True on success, False if there is no such timer.
		"""
		if name in self._timers:
			GLib.source_remove(self._timers[name])
			del self._timers[name]
			return True
		return False
	
	def cancel_all(self):
		""" Cancels all active timers """
		for x in self._timers:
			GLib.source_remove(self._timers[x])
		self._timers = {}
	
	def _callback(self, name, callback, *data, **kwdata):
		"""
		Removes name from list of active timers and calls real callback.
		"""
		del self._timers[name]
		callback(*data, **kwdata)
		return False