react-schedule 调度任务源码分析

// 立即执行
var IMMEDIATE_PRIORITY_TIMEOUT = -1;

var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000;
// 无限期等待
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;

// 任务存在最小堆上
//立即执行的任务队列
var taskQueue = [];
//延时任务队列
var timerQueue = [];

/**
* react-schedule调度器
* @param {number} priorityLevel 任务优先级
* @param {Function} callback 回调函数
* @param {object} options 可选配置
* @param {number} options.delay 延迟时间
* @returns 返回一个任务对象
*/
function unstable_scheduleCallback(priorityLevel, callback, options) {
//获取当前时间
var currentTime = getCurrentTime();
var startTime;
if (typeof options === "object" && options !== null) {
var delay = options.delay;
if (typeof delay === "number" && delay > 0) {
//延时任务
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}

var timeout;
//根据优先级获取超时时间
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
//计算任务到期时间
var expirationTime = startTime + timeout;
//创建任务对象
var newTask = {
id: taskIdCounter++, //任务id
callback, //回调函数
priorityLevel, //任务优先级
startTime, //任务开始时间
expirationTime, //任务到期时间
sortIndex: -1, //排序索引 用于最小堆排序(保证每次取出的任务都是优先级最高的||也就是到期时间最早的)
};
//开关
if (enableProfiling) {
newTask.isQueued = false;
}
//是否为延时任务
if (startTime > currentTime) {
newTask.sortIndex = startTime;
//推入延时任务队列
push(timerQueue, newTask);
//如果立即执行任务队列没有任务,并且当前延时任务队列的第一个任务就是当前任务
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
//延时开关阀
if (isHostTimeoutScheduled) {
//取消之前已存在的延时任务
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
}
// 设置超时时间
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
//立即执行任务队列
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
//报告信息收集
if (enableProfiling) {
markTaskStart(newTask, currentTime);
newTask.isQueued = true;
}
// 最终调用 requestHostCallback 进行任务的调度
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}

return newTask;
}
//不同的任务,最终调用的函数不一样
//普通任务:requestHostCallback(flushWork)
//延时任务:requestHostTimeout(handleTimeout, startTime - currentTime);
/**
* 进行实例化messageChannel 并调用 schedulePerformWorkUntilDeadline
* @param {Function} callback 回调函数
*/
function requestHostCallback(callback) {
//scheduledHostCallback->>> flushWork
scheduledHostCallback = callback;
//开关阀
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}

// 多平台兼容选择延时调度API 包装一个任务
let schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === "function") {
// Node.js and old IE.
schedulePerformWorkUntilDeadline = () => {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== "undefined") {
const channel = new MessageChannel();
const port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = () => {
port.postMessage(null);
};
} else {
schedulePerformWorkUntilDeadline = () => {
localSetTimeout(performWorkUntilDeadline, 0);
};
}

let startTime = -1;
/**
* 该方法实际上主要就是在调用 scheduledHostCallback(flushWork),返回一个布尔值,判断是否还有剩余的任务,如果还有,就是用 messageChannel 进行一个任务的包装,推入到任务队列。
*/
const performWorkUntilDeadline = () => {
//scheduledHostCallback->>>flushWork
if (scheduledHostCallback !== null) {
//当前时间
const currentTime = getCurrentTime();
startTime = currentTime;
//是否阻塞->是否还有时间执行任务 一帧->16.6ms
const hasTimeRemaining = true;
//是否需要继续执行 主要还是框架内部的错误捕获处理逻辑->避免抛出错误后导致任务无法继续执行
let hasMoreWork = true;
try {
//scheduledHostCallback->>>flushWork(是否有剩余时间,当前时间)
hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
} finally {
if (hasMoreWork) {
//任务调度 ->推入对应任务队列
schedulePerformWorkUntilDeadline();
} else {
//任务执行完毕
isMessageLoopRunning = false;
//释放任务->flushWork=null
scheduledHostCallback = null;
}
}
} else {
//任务执行完毕
isMessageLoopRunning = false;
}
//返还主线程控制权
needsPaint = false;
};

/**
* @param {boolean} hasTimeRemaining 是否还有剩余时间
* @param {number} initialTime 初始时间
*/
function flushWork(hasTimeRemaining, initialTime) {
//主要处理一些边角料
if (enableProfiling) {
markSchedulerUnsuspended(initialTime);
}

isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
isHostTimeoutScheduled = false;
cancelHostTimeout();
}

isPerformingWork = true;
const previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
//flushWork->workLoop 核心调用workLoop
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
const currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
if (enableProfiling) {
const currentTime = getCurrentTime();
markSchedulerSuspended(currentTime);
}
}
}

/**
* @param {boolean} hasTimeRemaining 是否还有剩余时间
* @param {number} initialTime 初始时间
*/
function workLoop(hasTimeRemaining, initialTime) {
//初始时间
let currentTime = initialTime;
//检查延时队列是否有到期任务,如有则推入任务队列
advanceTimers(currentTime);
//弹出当前最快到期的任务
currentTask = peek(taskQueue);
//如果当前任务不为空且没有暂停
while (currentTask !== null && !(enableSchedulerDebugging && isSchedulerPaused)) {
//currentTask.expirationTime > currentTime 任务没有到期
//hasTimeRemaining 是否还有剩余时间
//shouldYieldToHost() 是否需要让出主线程
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
const callback = currentTask.callback;
/**
* currentTask->{
* id: taskIdCounter++, //任务id
* callback, //回调函数
* priorityLevel, //任务优先级
* startTime, //任务开始时间
* expirationTime, //任务到期时间
* sortIndex: -1, //排序索引 用于最小堆排序(保证每次取出的任务都是优先级最高的||也就是到期时间最早的)
* }
*/
if (typeof callback === "function") {
currentTask.callback = null;
//currentPriorityLevel 当前任务的优先级
currentPriorityLevel = currentTask.priorityLevel;
//标记任务开始执行
const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
if (enableProfiling) {
markTaskRun(currentTask, currentTime);
}
//执行任务
const continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === "function") {
currentTask.callback = continuationCallback;
if (enableProfiling) {
markTaskYield(currentTask, currentTime);
}
} else {
if (enableProfiling) {
markTaskCompleted(currentTask, currentTime);
currentTask.isQueued = false;
}
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
//检查延时队列是否有到期任务,如有则推入任务队列
advanceTimers(currentTime);
} else {
//任务弹出
pop(taskQueue);
}
//弹出当前最快到期的任务进行执行
currentTask = peek(taskQueue);
}
// 如果不为空,代表还有更多的任务,那么回头外部的 hasMoreWork 拿到的就也是 true
if (currentTask !== null) {
return true;
} else {
//立即执行延时队列中的任务已经全部执行完毕 延时队列是否有任务
const firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
/**
* 延时队列到期的任务推入任务队列
* @param {number} currentTime 当前时间
*/
function advanceTimers(currentTime) {
let timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
//任务取消
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
//任务到期 推入任务队列
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
if (enableProfiling) {
markTaskStart(timer, currentTime);
timer.isQueued = true;
}
} else {
// 任务未到期 继续pending
return;
}
timer = peek(timerQueue);
}
}

let frameInterval = 5; //(ms)
// 如果当前时间已经超过了我们计算出来的下一个帧的时间,那么我们就需要让出主线程的控制权
function shouldYieldToHost() {
const timeElapsed = getCurrentTime() - startTime;
//这一帧还有时间执行任务 保持控制权
if (timeElapsed < frameInterval) {
return false;
}

//这一帧没有时间执行任务 让出控制权
if (enableIsInputPending) {
if (needsPaint) {
return true;
}
//是否有更高级的任务需要浏览器处理->用户输入、渲染、滚动等
if (timeElapsed < continuousInputInterval) {
// 有更高级的任务需要处理,让出控制权
if (isInputPending !== null) {
return isInputPending();
}
} else if (timeElapsed < maxInterval) {
// Yield if there's either a pending discrete or continuous input.
if (isInputPending !== null) {
return isInputPending(continuousOptions);
}
} else {
//返还控制权
return true;
}
}

return true;
}

实现一个简易的调度器

不考虑任务类别,细节处理,只实现基本调度功能

const ImmediatePriority = 1; //点击事件,用户输入
const UserBlockingPriority = 2; //动画,连续的用户操作 滚动,拖拽
const NormalPriority = 3; //数据获取,更新,手动更改组件状态
const LowPriority = 4; //非紧急任务
const IdlePriority = 5; //可能在浏览器空闲时执行

const IMMEDIATE_PRIORITY_TIMEOUT = -1;
const USER_BLOCKING_PRIORITY_TIMEOUT = 250;
const NORMAL_PRIORITY_TIMEOUT = 5000;
const LOW_PRIORITY_TIMEOUT = 10000;
const IDLE_PRIORITY_TIMEOUT = 1073741823;

/**
* @returns 获取当前时间
*/
const getCurrentTime = () => performance.now();
/**
* 根据优先级获取超时时间
* @param {number} type 任务类型
* @returns 任务超时时间
*/
const getTimeType = type => {
const timeType = {
1: IMMEDIATE_PRIORITY_TIMEOUT,
2: USER_BLOCKING_PRIORITY_TIMEOUT,
3: NORMAL_PRIORITY_TIMEOUT,
4: LOW_PRIORITY_TIMEOUT,
5: IDLE_PRIORITY_TIMEOUT,
};
return timeType[type] || 3;
};
class Schedule {
#tasks = []; //任务队列
#isExecuting = false; //是否正在执行任务
#channel = null; //任务通道
#sendMessage = null; //发送消息
constructor() {
this.#channel = new MessageChannel();
this.#sendMessage = this.#channel.port2;
this.#channel.port1.onmessage = this.#performWork.bind(this);
}
/**
* 收集任务信息
* @param {Function} callback 回调函数
* @param {number} priority 优先级
*/
scheduleCallback(callback, priority) {
let timeout = getTimeType(priority);
this.#tasks.push({
callback,
priority,
expireTime: getCurrentTime() + timeout,
});
//任务简单排序->取出最快到期的任务
this.#tasks.sort((a, b) => a.expireTime - b.expireTime);
this.#schedulePerformWorkUntilDeadline();
}
//任务调度
#schedulePerformWorkUntilDeadline() {
if (!this.#isExecuting) {
//调performWork,执行任务
this.#sendMessage.postMessage(null);
this.#isExecuting = true;
}
}
#performWork() {
this.#isExecuting = true;
this.#workLoop();
this.#isExecuting = false;
}
//判断是否需要让出执行权
#shouldYieldToHost() {
const currentTime = getCurrentTime();
const nextTask = this.#peek();
if (nextTask) {
return currentTime >= nextTask.expireTime;
}
return false;
}
//执行任务
#workLoop() {
//取出最快到期的任务
let nextTask = this.#peek();
while (nextTask) {
const { callback } = nextTask;
callback && callback();
this.#pop();
nextTask = this.#peek();
//判断是否需要让出执行权
if (this.#shouldYieldToHost()) {
break;
}
}
}
#peek() {
return this.#tasks[0] || null;
}
#pop() {
return this.#tasks.shift() || null;
}
}

//使用示例

const s = new Schedule();

s.scheduleCallback((...args) => {
console.log("用户点击事件--> 1 -->ImmediatePriority");
}, ImmediatePriority);
s.scheduleCallback((...args) => {
console.log("非紧急任务-> 4 -->LowPriority");
}, LowPriority);
s.scheduleCallback((...args) => {
console.log("数据获取,更新,手动更改组件状态--> 3 -->NormalPriority");
}, NormalPriority);
s.scheduleCallback((...args) => {
console.log("动画,连续的用户操作 滚动,拖拽> 2 -->NormalPriority", 2);
}, UserBlockingPriority);

输出结果

用户点击事件–> 1 –>ImmediatePriority
动画,连续的用户操作 滚动,拖拽> 2 –>NormalPriority 2
数据获取,更新,手动更改组件状态–> 3 –>NormalPriority
非紧急任务-> 4 –>LowPriority