Created
August 27, 2013 13:42
-
-
Save JonnyFunFun/6353681 to your computer and use it in GitHub Desktop.
Simple decorator to use to schedule a function to occur every X seconds
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 threading | |
class ReoccuringTask(object): | |
def __init__(self, recurrence): | |
self.schedule = recurrence | |
def __call__(self, orig_func): | |
decorator_self = self | |
def wrap(*args, **kwargs): | |
ev = threading.Event() | |
def loop(): | |
while not ev.wait(decorator_self.schedule): | |
orig_func(*args, **kwargs) | |
thread = threading.Thread(target=loop) | |
thread.daemon = True | |
thread.start() | |
return ev | |
return wrap | |
# And this is how you use it: | |
@ReocurringTask(1) | |
def my_task(x): | |
print x | |
my_task('A') | |
my_task('B') # both of these will run every second |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment