forked from DataDog/datadogpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperiodic_timer.py
More file actions
36 lines (30 loc) · 1.11 KB
/
Copy pathperiodic_timer.py
File metadata and controls
36 lines (30 loc) · 1.11 KB
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
# Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2015-Present Datadog, Inc
"""
A small class to run a task periodically in a thread.
"""
from threading import Thread, Event
import sys
class PeriodicTimer(Thread):
def __init__(self, interval, function, *args, **kwargs):
Thread.__init__(self)
self.daemon = True
assert interval > 0
self.interval = interval
assert function
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def end(self):
self.finished.set()
def run(self):
while not self.finished.wait(self.interval):
try:
self.function(*self.args, **self.kwargs)
except Exception:
# If `sys` is None, it means the interpreter is shutting down
# and it's very likely the reason why we got an exception.
if sys is not None:
raise