-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregister_a_function.py
More file actions
38 lines (28 loc) · 924 Bytes
/
register_a_function.py
File metadata and controls
38 lines (28 loc) · 924 Bytes
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
from time import sleep
from threading import Thread
# Using a decorator to register a function for something like an event
# The decoration saves a reference to the decorated function, but it just
# returns the same function, so no change is made
class Timer:
def __init__(self):
self.timer_thread = Thread(target=self.timer_tick, daemon=True)
self.registered_fn = None
def timer_tick(self):
while True:
sleep(2)
self.registered_fn()
def start(self):
print('Starting timer')
self.timer_thread.start()
# This is the decorator function. Notice we are just saving a
# reference to it and returning the same function back
def register(self, fn):
print('Registering function to timer')
self.registered_fn = fn
return fn
timer = Timer()
@timer.register
def say_hi():
print('hi')
timer.start()
sleep(999)