Last active
August 29, 2015 14:13
-
-
Save tkaemming/b1723c88ed9d86b3d13f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import atexit | |
import time | |
from threading import ( | |
Event, | |
Lock, | |
Thread, | |
) | |
def ticker(interval, function, flush=None): | |
""" | |
Runs the provided function at the given interval. | |
""" | |
cancelled = Event() | |
def finish(): | |
if flush is None: | |
return # nothing to do | |
with finish.lock: | |
if not finish.executed: | |
flush() | |
finish.executed = True | |
finish.lock = Lock() | |
finish.executed = False | |
def run(): | |
while not cancelled.is_set(): | |
time.sleep(interval) | |
function() | |
finish() | |
t = Thread(None, run) | |
t.daemon = True | |
t.start() | |
if flush: | |
atexit.register(finish) | |
return cancelled.set | |
if __name__ == '__main__': | |
import itertools | |
import sys | |
counter = itertools.count(1) | |
queue = [] | |
def ping(): | |
print 'ping', time.time() | |
queue.append(next(counter)) | |
def flush(): | |
print queue | |
cancel = ticker(1, ping, flush) | |
time.sleep(int(sys.argv[1])) | |
cancel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment