pnpm
Version:
Fast, disk space efficient package manager
97 lines (77 loc) • 2.33 kB
JavaScript
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
import ScheduledTask from './ScheduledTask'
import { runTask } from '../task'
export default function Scheduler (timer, timeline) {
this.timer = timer
this.timeline = timeline
this._timer = null
this._nextArrival = Infinity
var self = this
this._runReadyTasksBound = function () {
self._runReadyTasks(self.now())
}
}
Scheduler.prototype.now = function () {
return this.timer.now()
}
Scheduler.prototype.asap = function (task) {
return this.schedule(0, -1, task)
}
Scheduler.prototype.delay = function (delay, task) {
return this.schedule(delay, -1, task)
}
Scheduler.prototype.periodic = function (period, task) {
return this.schedule(0, period, task)
}
Scheduler.prototype.schedule = function (delay, period, task) {
var now = this.now()
var st = new ScheduledTask(now + Math.max(0, delay), period, task, this)
this.timeline.add(st)
this._scheduleNextRun(now)
return st
}
Scheduler.prototype.cancel = function (task) {
task.active = false
if (this.timeline.remove(task)) {
this._reschedule()
}
}
Scheduler.prototype.cancelAll = function (f) {
this.timeline.removeAll(f)
this._reschedule()
}
Scheduler.prototype._reschedule = function () {
if (this.timeline.isEmpty()) {
this._unschedule()
} else {
this._scheduleNextRun(this.now())
}
}
Scheduler.prototype._unschedule = function () {
this.timer.clearTimer(this._timer)
this._timer = null
}
Scheduler.prototype._scheduleNextRun = function (now) { // eslint-disable-line complexity
if (this.timeline.isEmpty()) {
return
}
var nextArrival = this.timeline.nextArrival()
if (this._timer === null) {
this._scheduleNextArrival(nextArrival, now)
} else if (nextArrival < this._nextArrival) {
this._unschedule()
this._scheduleNextArrival(nextArrival, now)
}
}
Scheduler.prototype._scheduleNextArrival = function (nextArrival, now) {
this._nextArrival = nextArrival
var delay = Math.max(0, nextArrival - now)
this._timer = this.timer.setTimer(this._runReadyTasksBound, delay)
}
Scheduler.prototype._runReadyTasks = function (now) {
this._timer = null
this.timeline.runTasks(now, runTask)
this._scheduleNextRun(this.now())
}