Created
April 23, 2017 01:36
-
-
Save dyjjones/993f2e4249c7cba03121ac55e41722a7 to your computer and use it in GitHub Desktop.
threaded scheduler
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 sched, threading, time | |
from concurrent.futures import ThreadPoolExecutor | |
from math import ceil | |
class ThreadedScheduler: | |
def __init__(self, f, delay=0, period=1, poolsize=2): | |
# delay is initial delay from now until first schedule run | |
# period is the amount of time between each call | |
# though that probably still contains problems | |
# if the time to run each call to f exceeds 1 second | |
# that could be fixed by running each f call in another thread | |
self.f = f | |
self.delay = delay | |
self.period = period | |
# period + 1 is a precaution against long-lasting | |
# functions, i.e. it should work against functions | |
# that take just under (period + 1) seconds | |
# but anything longer wll still cause problems | |
# where it blocks. | |
# if you're sleeping, or hashing passwords, or trying to | |
#download over a slow connection, that could exceed | |
# the above definition of long and cause such a problem | |
min_pool_size = ceil(period) + 1 | |
if poolsize < min_pool_size: | |
poolsize = min_pool_size | |
self.pool = ThreadPoolExecutor(poolsize) | |
self.thread = threading.Thread(target=self.run) | |
self.thread.start() | |
def run(self): | |
self.scheduler = sched.scheduler(time.time, time.sleep) | |
self.scheduler.enter(self.delay,1,self.f_wrapper, (time.time()+self.delay,)) | |
self.scheduler.run() | |
def f_wrapper(self, t): | |
self.pool.submit(self.f) | |
t += self.period | |
self.scheduler.enterabs(t, 1, self.f_wrapper, (t,)) | |
if __name__ == '__main__': | |
scheduler = ThreadedScheduler(lambda: (print('tacos'), time.sleep(5), print('done')), 3, poolsize=6) | |
print('burrito') | |
def create_clock(scheduler=scheduler, tick_delay=20, timer=0): | |
pass | |
while True: | |
print('ordering tacos..') | |
time.sleep(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can I meepo?