Created
August 14, 2014 02:56
-
-
Save codeskyblue/1b8dca59879b193a200d to your computer and use it in GitHub Desktop.
use goless to implement monitor
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 goless | |
import time | |
import gevent | |
from gevent import monkey | |
monkey.patch_all() | |
def time_after(seconds): | |
c = goless.chan() | |
def _fn(): | |
gevent.sleep(seconds) | |
c.send(True) | |
goless.go(_fn) | |
return c | |
class Monitor(object): | |
def __init__(self): | |
self._chan = goless.chan(0) | |
self._tasks = [] | |
self._running = True | |
self._cycle = 0.5 | |
goless.go(self._drain) | |
def start(self): | |
self._chan.send(True) | |
def stop(self): | |
self._chan.send(False) | |
def addfunc(self, func, *args, **kwargs): | |
self._tasks.append([func, args, kwargs]) | |
def _drain(self): | |
while True: | |
cases = [goless.rcase(self._chan), goless.rcase(time_after(self._cycle))] | |
chosen, is_start = goless.select(cases) | |
if chosen is cases[0]: | |
self._running = is_start | |
continue | |
if not self._running: | |
continue | |
for task in self._tasks: | |
func, args, kwargs = task | |
goless.go(func, *args, **kwargs) | |
m = Monitor() | |
def say(msg = 'hello'): | |
print 'say:', msg | |
m.addfunc(say, 'hi') | |
m.start() | |
gevent.sleep(4) | |
m.stop() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment