Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created February 5, 2011 16:07
Show Gist options
  • Save robotlolita/812551 to your computer and use it in GitHub Desktop.
Save robotlolita/812551 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import time
from collections import defaultdict
class IdleProcess(object):
"""Process data when CPU is idle
"""
def __init__(self):
self.poll = []
self.listeners = defaultdict(list)
def listen(self, event, callback):
"""Listens to an event
"""
self.listeners[event].append(callback)
def deafen(self, event, callback):
"""Stop listening to an event
"""
self.listeners[event].remove(callback)
def process(self):
"""Process the next event in the poll.
"""
if self.poll:
event = self.poll.pop(0)
callbacks = self.listeners[event['kind']]
for callback in callbacks:
callback(event)
def post(self, kind, **kwargs):
"""Post a new event. When the application has some time, it'll process
them and call the right functions that are waiting for them.
"""
kwargs['kind'] = kind
self.poll.append(kwargs)
# Some functions that are called when the event they're waiting for happens.
def get10(evt):
print "10 GET!!!"
def get50(evt):
print "50 GET!!!"
def get100(evt):
print "100 GET!!!"
def get1000(evt):
print "1000 GET!!!"
def any_get(evt):
print "-- %d GET" % evt['current']
def setup(idle):
"""Mark some functions for listening to events.
"""
idle.listen("10get", get10)
idle.listen("50get", get50)
idle.listen("100get", get100)
idle.listen("1000get", get1000)
idle.listen("get", any_get)
def main(idle):
"""Main program.
"""
current = 1
steps = 5
while True:
steps -= 1
if not steps:
print "Now processing: %d" % current
idle.post("get", current=current)
idle.post("%dget" % current, current=current)
current += 1
steps = 5
idle.process() # let events be handled properly
time.sleep(0.1)
if __name__ == '__main__':
idle = IdleProcess()
setup(idle)
main(idle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment