Debian Codegraph @

killtimer.py

raw
1 #!/usr/bin/python3
2
3 ## system-config-printer
4
5 ## Copyright (C) 2010, 2011, 2012, 2013, 2014 Red Hat, Inc.
6 ## Authors:
7 ## Tim Waugh <[email protected]>
8
9 ## This program is free software; you can redistribute it and/or modify
10 ## it under the terms of the GNU General Public License as published by
11 ## the Free Software Foundation; either version 2 of the License, or
12 ## (at your option) any later version.
13
14 ## This program is distributed in the hope that it will be useful,
15 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ## GNU General Public License for more details.
18
19 ## You should have received a copy of the GNU General Public License
20 ## along with this program; if not, write to the Free Software
21 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
23 import threading
24
25 from gi.repository import GLib
26
27 from debug import *
28
29 class KillTimer:
30 def __init__ (self, timeout=30, killfunc=None):
31 self._timeout = timeout
32 self._killfunc = killfunc
33 self._holds = 0
34 self._add_timeout ()
35 self._lock = threading.Lock()
36
37 def _add_timeout (self):
38 self._timer = GLib.timeout_add_seconds (self._timeout, self._kill)
39
40 def _kill (self):
41 debugprint ("Timeout (%ds), exiting" % self._timeout)
42 if self._killfunc:
43 self._killfunc ()
44 else:
45 sys.exit (0)
46
47 def add_hold (self):
48 self._lock.acquire()
49 if self._holds == 0:
50 debugprint ("Kill timer stopped")
51 GLib.source_remove (self._timer)
52
53 self._holds += 1
54 self._lock.release()
55
56 def remove_hold (self):
57 self._lock.acquire()
58 if self._holds > 0:
59 self._holds -= 1
60 if self._holds == 0:
61 debugprint ("Kill timer started")
62 self._add_timeout ()
63 self._lock.release()
64
65 def alive (self):
66 self._lock.acquire()
67 if self._holds == 0:
68 GLib.source_remove (self._timer)
69 self._add_timeout ()
70 self._lock.release()