Skip to content

Instantly share code, notes, and snippets.

@tkaemming
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkaemming/b1723c88ed9d86b3d13f to your computer and use it in GitHub Desktop.
Save tkaemming/b1723c88ed9d86b3d13f to your computer and use it in GitHub Desktop.
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