2014-10-05 16:25:31 +08:00
|
|
|
import asyncio
|
2014-12-10 13:04:18 +08:00
|
|
|
from time import time
|
2014-10-05 16:25:31 +08:00
|
|
|
|
|
|
|
from artiq.management.worker import Worker
|
|
|
|
|
|
|
|
|
|
|
|
class Scheduler:
|
2014-12-08 19:22:02 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.worker = Worker(*args, **kwargs)
|
2014-12-10 13:04:18 +08:00
|
|
|
self.currently_executing = None
|
|
|
|
self.next_rid = 0
|
2014-12-09 16:26:50 +08:00
|
|
|
self.queued = []
|
|
|
|
self.queue_count = asyncio.Semaphore(0)
|
2014-10-05 16:25:31 +08:00
|
|
|
|
2014-12-10 13:04:18 +08:00
|
|
|
def new_rid(self):
|
|
|
|
r = self.next_rid
|
|
|
|
self.next_rid += 1
|
|
|
|
return r
|
|
|
|
|
2014-10-23 18:48:03 +08:00
|
|
|
@asyncio.coroutine
|
|
|
|
def start(self):
|
|
|
|
self.task = asyncio.Task(self._schedule())
|
|
|
|
yield from self.worker.create_process()
|
2014-10-05 16:25:31 +08:00
|
|
|
|
2014-10-23 18:48:03 +08:00
|
|
|
@asyncio.coroutine
|
|
|
|
def stop(self):
|
|
|
|
self.task.cancel()
|
|
|
|
yield from asyncio.wait([self.task])
|
|
|
|
del self.task
|
|
|
|
yield from self.worker.end_process()
|
2014-10-05 16:25:31 +08:00
|
|
|
|
2014-10-23 18:48:03 +08:00
|
|
|
def run_once(self, run_params, timeout):
|
2014-12-10 13:04:18 +08:00
|
|
|
rid = self.new_rid()
|
|
|
|
self.queued.append((rid, run_params, timeout))
|
2014-12-09 16:26:50 +08:00
|
|
|
self.queue_count.release()
|
2014-12-10 13:04:18 +08:00
|
|
|
return rid
|
|
|
|
|
|
|
|
def cancel_once(self, rid):
|
|
|
|
idx = next(idx for idx, (qrid, _, _) in enumerate(self.queued)
|
|
|
|
if qrid == rid)
|
|
|
|
del self.queued[idx]
|
|
|
|
|
|
|
|
def get_schedule(self):
|
|
|
|
if self.currently_executing is None:
|
|
|
|
ce = None
|
|
|
|
else:
|
|
|
|
rid, run_params, timeout, t = self.currently_executing
|
|
|
|
ce = rid, run_params, timeout, time() - t
|
|
|
|
return ce, self.queued
|
|
|
|
|
|
|
|
def run_periodic(self, run_params, timeout, period):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def cancel_periodic(self, prid):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def _run(self, rid, run_params, timeout):
|
|
|
|
self.currently_executing = rid, run_params, timeout, time()
|
|
|
|
result = yield from self.worker.run(run_params, timeout)
|
|
|
|
self.currently_executing = None
|
|
|
|
return result
|
2014-10-05 16:25:31 +08:00
|
|
|
|
2014-10-23 18:48:03 +08:00
|
|
|
@asyncio.coroutine
|
|
|
|
def _schedule(self):
|
2014-10-05 16:25:31 +08:00
|
|
|
while True:
|
2014-12-09 16:26:50 +08:00
|
|
|
yield from self.queue_count.acquire()
|
2014-12-10 13:04:18 +08:00
|
|
|
rid, run_params, timeout = self.queued.pop(0)
|
|
|
|
result = yield from self._run(rid, run_params, timeout)
|
|
|
|
print(rid, result)
|