def __init__(self, secs, func, args=(), kwargs=None): assert hasattr(func, "__call__"), "function argument must be callable" self.func = func self.args = args self.kwargs = kwargs self._glet = glet = greenlet(self.func, state.mainloop) self.waketime = waketime = time.time() + secs self.cancelled = False scheduler.schedule_at(waketime, glet)
def schedule(target=None, args=(), kwargs=None): '''set up a greenlet or function to run later if *target* is a function, it is wrapped in a new greenlet. the greenlet will be run at an undetermined time. also usable as a decorator''' if target is None: def decorator(target): return schedule(target, args=args, kwargs=kwargs) return decorator if isinstance(target, greenlet): glet = target else: if args or kwargs: inner_target = target def target(): inner_target(*args, **(kwargs or {})) glet = greenlet(target, state.mainloop) state.paused.append(glet) return target
def schedule_at(unixtime, target=None, args=(), kwargs=None): '''set up a greenlet or function to run at the specified timestamp if *target* is a function, it is wrapped in a new greenlet. the greenlet will be run sometime after *unixtime*, a timestamp''' kwargs = kwargs or {} if target is None: def decorator(target): return schedule_at(unixtime, target, args=args, kwargs=kwargs) return decorator if isinstance(target, greenlet): glet = target else: if args or kwargs: inner_target = target def target(): inner_target(*args, **kwargs) glet = greenlet(target, state.mainloop) bisect.insort(state.timed_paused, (unixtime, glet)) return target
def greenlet(func, args=(), kwargs=None): """create a new greenlet from a function and arguments :param func: the function the new greenlet should run :type func: function :param args: any positional arguments for the function :type args: tuple :param kwargs: any keyword arguments for the function :type kwargs: dict or None the only major difference between this function and that of the basic greenlet api is that this one sets the new greenlet's parent to be the greenhouse main loop greenlet, which is a requirement for greenlets that will wind up in the greenhouse scheduler. """ if args or kwargs: def target(): return func(*args, **(kwargs or {})) else: target = func return compat.greenlet(target, state.mainloop)