你總是可以實現自己的調度與heapq
。這裏有一個調度器,其中延遲是相對的一個簡單的例子來start
:
import heapq
import time
def fun(after, s):
print('{} after {} seconds: {}'.format(time.time(), after, s))
class Sched:
def __init__(self):
self.tasks = []
def add_task(self, delay_seconds, priority, callback, args):
task = (delay_seconds, priority, callback, args)
heapq.heappush(self.tasks, task)
def start(self):
self.start_time = time.monotonic()
while self.tasks:
now = time.monotonic()
delta = now - self.start_time
nxt = self.tasks[0][0]
if delta < nxt:
time.sleep(nxt - delta)
else:
_, _, callback, args = heapq.heappop(self.tasks)
callback(*args)
sched = Sched()
sched.add_task(5, 1, fun, (5, 'second'))
sched.add_task(5, 0, fun, (5, 'first'))
sched.add_task(7, 0, fun, (7, 'third'))
print(time.time(), 'start')
sched.start()
print(time.time(), 'end')
輸出:
1485623736.9788322 start
1485623741.9809415 after 5 seconds: first
1485623741.9809415 after 5 seconds: second
1485623743.9846892 after 7 seconds: third
1485623743.9846892 end
請注意,請在任務不完全運行。這是因爲可能是時間的sleep
的侷限性和需要來執行以前的任務。
謝謝!雖然這是封鎖。是否也被調度?我總是設法誤解Python文檔,而不是其他任何文檔。 –
@ DouglasMyers-Turnbull你可以在兩種模式下['運行'](https://docs.python.org/3/library/sched.html#sched.scheduler.run),默認爲阻塞。 – niemmi