Add GrabResult and SetupEvent, for synchronicity.
authorFabien Ninoles <fabien@tzone.org>
Sun, 21 Mar 2010 21:40:40 -0400
changeset 4 76ba9b3a9e1c
parent 3 00b6708d1852
child 5 eb1133af54ed
Add GrabResult and SetupEvent, for synchronicity.
scheduler.py
--- a/scheduler.py	Sun Mar 21 20:56:44 2010 -0400
+++ b/scheduler.py	Sun Mar 21 21:40:40 2010 -0400
@@ -72,11 +72,32 @@
         self.tail.Chain(task.head)
         self.tail = task.tail
 
+    def GrabResult(self, data = None):
+        if data is None:
+            data = {}
+        def SetResult(result):
+            data["result"] = result
+            return result
+        def SetError(error):
+            data["error"] = error
+        self.AddCallback(SetResult, SetError)
+        return data
+
+    def SetupEvent(self, event = None, data = None):
+        if not event:
+            event = threading.Event()
+        def SetEvent(dummy):
+            event.set()
+        self.AddCallback(SetEvent, SetEvent)
+        return event
+
+##
+# Helper class
 class ThreadedTask(Task):
     def __init__(self, func, *args, **kwargs):
         super(ThreadedTask, self).__init__(func, *args, **kwargs)
         self.head.threaded = True
-    
+
 class Scheduler(threading.Thread):
 
     class _SchedulerStop(Exception):
@@ -148,8 +169,8 @@
         self.AddTask(Task(RaiseSchedulerStop))
         self.join()
 
-    def AddTask(self, task, blocking = True):
-        self.tasks.put(task, blocking)
+    def AddTask(self, task):
+        self.tasks.put(task)
 
     def _AddJob(self, task, cb, result, error, traceback):
 
@@ -218,6 +239,7 @@
             global count
             print name, "wakes up!"
             count -= 1
+            return name
 
         task = Task(Initialize, name, seconds)
         task.AddThreadedCallback(Blocking)
@@ -233,6 +255,17 @@
     while count > 0:
         logging.debug("Count = %d", count)
         sleep(1)
+
+    # Check for King Toto sleep
+    task = AsyncCall("King Toto", 5)
+    data = task.GrabResult()
+    event = task.SetupEvent()
+    scheduler.AddTask(task)
+    try:
+        event.wait(10)
+        print "data = %r" % (data,)
+    except:
+        logging.exception("Error occured on wait")
     logging.info("Stopping scheduler")
     StopScheduler()
     logging.info("The End.")