This repository has been archived by the owner on Oct 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresumetimer.py
59 lines (51 loc) · 1.64 KB
/
resumetimer.py
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
import os
import time
import threading
MAX_PAUSE_TIME = 7200
class ResumableTimer:
'''
Resumable timer will run the given callback function
after the given timeout. The Timer can be paused more than once
until the MAX_PAUSE_TIME has been reached
'''
def __init__(self, timeout, callback):
self.timeout = timeout
self.callback = callback
self.timer = threading.Timer(timeout, callback)
self.start_time = time.time()
self.pause_time = 0
self.pause_timer = None
def start(self):
self.timer.start()
def pause(self,pause_seconds):
'''
Stop the main timer and start the pause timer. Once the
pause timer has run to completion the main timer will
proceed with rest of its timeout.
'''
cur_time = time.time()
if self.pause_timer is None:
self.pause_time = cur_time
self.timer.cancel()
else:
elapsed = cur_time - self.pause_time
if elapsed + pause_seconds > MAX_PAUSE_TIME:
ret = -2
if pause_seconds == 0:
ret = 0
self.pause_timer.cancel()
self.resume()
return ret
self.pause_timer = threading.Timer(pause_seconds,
self.resume)
self.pause_timer.start()
return 0
def resume(self):
'''
Resume the main timer and schedule the callback function
to be executed
'''
self.timer = threading.Timer(
self.timeout - (self.pause_time - self.start_time),
self.callback)
self.timer.start()