【React】任务调度scheduler的实现(二)

222 阅读5分钟

本次需要涉及到的文件目录有:

1647834779341-a6f1b3ec-8d51-4a9a-a28f-122a6158f74e.png

实现任务的优先级

  1. 现在我们有calculate和calculate1共2个任务,我们再新增一个任务3。
/ index.js
import { 
    scheduleCallback, // 调度回调,计划执行回调
    shouldYield, // 应该放弃执行权/中断
 } from './scheduler';
let result = 0, result2 = 0, result3 = 0;
let i = 0, i2 = 0, i3= 0;
/**
 * 要想能过方便的让任务能过 暂停和恢复,需要数据结构支持
 * @returns 
 */
function calculate() {
    // shouldYield如果任务没有结束,并且浏览器分配的时间片(一般是4ms)已经到期了,就会放弃本任务的执行,
    // 把线程的资源交还给浏览器,让浏览器执行更高优先级的工作,比如页面绘制,响应用户输入
    for (; i < 1000000 && (!shouldYield()); i++) {
        result += 1;
    }
    // 当推出本任务的时候,如果任务没有完成,返回任务函数本身,如果任务完成了就返回null
    if (i < 1000000) {
        return calculate;
    } else {
        console.log(result);
        return null;
    }
}
function calculate2() {
    for (; i2 < 2000000 && (!shouldYield()); i2++) {
        result2 += 1;
    }
    if (i2 < 2000000) {
        return calculate2;
    } else {
        console.log(result2);
        return null;
    }
}

function calculate3() {
    for (; i3 < 1000000 && (!shouldYield()); i3++) {
        result3 += 1;
    }
    if (i3 < 1000000) {
        return calculate3;
    } else {
        console.log("result3", result3);
        return null;
    }
}

scheduleCallback(calculate);
scheduleCallback(calculate2);
scheduleCallback(calculate3);

1647581636059-c0228ae2-8c65-4713-832f-5a3764f7d1c0.png

可以观察到,在浏览器执行中代码会按照3个函数回调顺序去依此执行,那我们如果现在希望calculate3先执行,让后来的任务先执行呢?

  1. 为解决这个问题react引入优先级的概念。我们在src下新增一个关于调度优先级的文件SchedulerPriorities.js,有如下6个优先级的分类,从上往下优先级越来越低。
// scheduler/src/SchedulerPriorities.js
export const NoPriority = 0; // 没有任何优先级
export const ImmediatePriority = 1; // 立即执行的优先级,级别最高
export const UserBlockingPriority = 2; // 用户阻塞级别的优先级
export const NormalPriority = 3; // 正常优先级
export const LowPriority = 4; // 较低的优先级
export const IdlePriority = 5; // 优先级最低,表示可以闲置
  1. 定义好我们的优先级后,我们还需要用到最小堆的知识去管理我们的优先级。我们需要具备以下的知识:
  • 二叉树:每个节点至多有2个节点
  • 完全二叉树:叶子结点只能出现在最下层和次下层,且最下层的叶子结点集中在树的左部。
  • 满二叉树:除最后一层无任何子节点外,每一层的所有节点都有两个节点的二叉树
  • 最小堆:是一种经过排序的完全二叉树,所有的父节点小于我们的子节点,根最小
  1. 新建一个SchedulerMinHeap.js文件,用来实现我们的最小堆算法,该模块包含了3个方法,分别是push,peek,pop。
  • peek:查看堆顶的元素
  • push:添加一个元素,并调整最小堆(从最后一个开始新增,然后对比向上调整树的结构)
  • pop:取出并删除堆顶的元素,并调整最小堆。(移除堆顶的元素,然后把堆尾的元素放到堆顶,向下调整树的结构)
// scheduler/src/SchedulerMinHeap.js
export function push(heap, node) {
    const index = heap.length;
    heap.push(node);
    siftUp(heap, node, index);
}
export function peek(heap) {
    const first = heap[0];
    return first === undefined ? null : first;
}
export function pop(heap) {
    const first = heap[0];
    if (first !== undefined) {
        const last = heap.pop();
    if (last !== first) {
        heap[0] = last;
        siftDown(heap, last, 0);
    }
        return first;
    } else {
        return null;
    }
}

function siftUp(heap, node, i) {
    let index = i;
    while (true) {
        const parentIndex = index - 1 >>> 1;
        const parent = heap[parentIndex];
        if (parent !== undefined && compare(parent, node) > 0) {
            heap[parentIndex] = node;
            heap[index] = parent;
            index = parentIndex;
        } else {
            return;
        }
    }
}

function siftDown(heap, node, i) {
    let index = i;
    const length = heap.length;
    while (index < length) {
        const leftIndex = (index + 1) * 2 - 1;
        const left = heap[leftIndex];
        const rightIndex = leftIndex + 1;
        const right = heap[rightIndex]; 
        if (left !== undefined && compare(left, node) < 0) {
            if (right !== undefined && compare(right, left) < 0) {
                heap[index] = right;
                heap[rightIndex] = node;
                index = rightIndex;
            } else {
                heap[index] = left;
                heap[leftIndex] = node;
                index = leftIndex;
            }
        } else if (right !== undefined && compare(right, node) < 0) {
            heap[index] = right;
            heap[rightIndex] = node;
            index = rightIndex;
        } else {
            return;
        }
    }
}

function compare(a, b) {
    const diff = a.sortIndex - b.sortIndex;
    return diff !== 0 ? diff : a.id - b.id;
}
  1. 修改我们的Scheduler.js文件,引入我们的优先级,以及最小堆push,peek,pop三个方法。给每个优先级规定一个超时时间,用来表示我的每个任务的优先级,从SchedulerHostConfig再引入getCurrentTime方法【注:记得将getCurrentTime在SchedulerHostConfig导出】
// scheduler/src/Scheduler.js
import { 
    requestHostCallback,
    shouldYieldToHost as shouldYield,
    getCurrentTime
} from './SchedulerHostConfig';
import { push, pop, peek } from './SchedulerMinHeap';
import { ImmediatePriority, UserBlockingPriority, NormalPriority, LowPriority, IdlePriority } from './SchedulerPriorities';

// 每个优先级对应的任务对应一个过期时间
var maxSigned31BitInt = 1073741823;
var IMMEDIATE_PRIORITY_TIMEOUT = -1;
var USER_BLOCKING_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000;
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;

// ...
function scheduleCallback (callback) {
    // ...
}
/**
 * 依次执行任务队列中的任务
 */
function flushWork() {
   // ...
} 

function workLoop() {
    // ...
}

export {
   // ...
}
// scheduler/src/SchedulerHostConfig.js
export function getCurrentTime() {
    return performance.now();
}
  1. 向最小堆里面添加数据,最小堆会去先比较数据的sortIndex再去比较id值,最小堆里存储的数据的数据结构为:
{
        id: taskIdCounter++, // 每一个任务都有一个自增的id
        callback, // 真正要执行的函数
        priorityLevel, // 优先级保存下来
        expirationTime, // 过期时间
        startTime, // 任务开始的时间
        sortIndex: expirationTime // 排序值
}

修改我们的Scheduler.js文件

// scheduler/src/Scheduler.js
// ...
// 用于任务自增的id
let taskIdCounter = 0;

// 为了同时调度多个任务,而不会互相覆盖,需要搞一个任务队列
let taskQueue = [];
// 当前的任务
let currentTask;
/**
 * 调度一个回调任务
 * @param {*} callback 
 */
function scheduleCallback (priorityLevel, callback) {
    // 获取当前时间
    let currentTime = getCurrentTime();
    // 此任务的开始时间
    let startTime = currentTime;
    // 计算超时时间
    let timeout;
    switch (priorityLevel) {
        case ImmediatePriority: 
            timeout = IMMEDIATE_PRIORITY_TIMEOUT; 
            break;
        case UserBlockingPriority: 
            timeout = USER_BLOCKING_TIMEOUT; 
            break;
        case NormalPriority: 
            timeout = NORMAL_PRIORITY_TIMEOUT; 
            break;
        case LowPriority: 
            timeout = LOW_PRIORITY_TIMEOUT; 
            break;
        case IdlePriority: 
            timeout = IDLE_PRIORITY_TIMEOUT; 
            break;
    }
    // 计算一个过期时间 = 当前时间 + 超时时间
    let expirationTime = startTime + timeout;
    let newTask = {
        id: taskIdCounter++, // 每一个任务都有一个自增的id
        callback, // 真正要执行的函数
        priorityLevel, // 优先级保存下来
        expirationTime, // 过期时间
        startTime, // 任务开始的时间
        sortIndex: -1 // 排序值
    }
    newTask.sortIndex = expirationTime;
    // 向最小堆里添加一个新的任务,先比较优先级(索引)再比id
    push(taskQueue, newTask);
    // taskQueue.push(callback);
    requestHostCallback(flushWork);
}

function flushWork() {
    // ...
}

function workLoop() {
   // ...
}
// ...
  1. 那么根据优先级怎么去执行我们的任务?找到我们的workLoop工作循环,将我们的当前任务用peek取出最小堆堆顶的元素,同时修改我们推出工作循环的条件,只有满足任务没有过期,且时间片到期,任务才会到下一个时间片执行,如果任务过期,将会以同步执行的方式将这个任务执行完。由于我们队列中存储的数据类型以及是一个对象,所以我们真正要执行的回调函数为currentTask.callback。
// scheduler/src/Scheduler.js
/**
 * 依次执行任务队列中的任务
 */
function flushWork(currentTime) {
    return workLoop(currentTime);
}
/**
 * 在这里有两个打断或者停止执行
 * 在执行每一个任务的时候,如果时间片到期了会退出workLoop
 * 另一个是在执行currentTask的时候,如果时间片到期了,也会退出执行
 * @returns 
 */
function workLoop(currentTime) {
    // 取出优先队列中的优先级最高的堆顶元素,也就是过期时间最早的元素
    currentTask = peek(taskQueue); // 等同于currentTask = taskQueue[0];
    while(currentTask) {
        // 如果说时间片到期了,就退出循环
        // 如果说过期时间大于当前时间,并且时间片到期就推出执行 => 如果说已经过期了,及时时间片到期了,也需要继续执行 => 如果一个任务过期了,则不再考虑所谓时间配额问题了,立刻马上权利执行结束
        if (currentTask.expirationTime > currentTime && shouldYield()) {
            break;
        }
        // 取出当前任务的回调函数calculate
        const callback = currentTask.callback;
        // 如果它是一个函数的话
        if (typeof callback === 'function') {
            // 先清空
            currentTask.callback = null;
            // 判断此任务是否过期
            const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
            const continuationCallback = callback(didUserCallbackTimeout);
            if (typeof continuationCallback === 'function') {
                currentTask.callback = continuationCallback;
            } else {
                pop(taskQueue);
            }
        } else {
            // 如果任务的callback属性不是函数,则将此任务出队,这个在后面的取消任务的会用到
            pop(taskQueue);
        }
        // 继续取出最小堆堆顶的任务
        currentTask = peek(taskQueue);
    }
    return currentTask;
}
  1. 当前时间需要在我们执行调度的回调函数时传入当前时间currentTime,去修改SchedulerHostConfig.js文件
// scheduler/src/SchedulerHostConfig.js
/**
 * 执行工作直到截止时间
 */
function performWorkUntilDeadline() {
    // ...
    const hasMoreWork = scheduledHostCallback(currentTime);
    // ...
}
  1. 将我们的优先级在Scheduler.js导出
// scheduler/src/Scheduler.js
export {
    scheduleCallback,
    shouldYield,
    ImmediatePriority, 
    UserBlockingPriority, 
    NormalPriority, 
    LowPriority, 
    IdlePriority
}
  1. 在我们的index.js中引入我们的优先级,同时在回调函数中参入参数判断任务过期时间是否已经到了,修改判断条件为&& (!shouldYield() || didTimeout)。执行scheduleCallback的同时将我们任务的优先级传进去。
import { 
    scheduleCallback, // 调度回调,计划执行回调
    shouldYield, // 应该放弃执行权/中断
    ImmediatePriority, 
    UserBlockingPriority, 
    NormalPriority, 
    LowPriority, 
    IdlePriority,
 } from './scheduler';
 let result = 0, result2 = 0, result3 = 0;
 let i = 0, i2 = 0, i3= 0;
/**
 * 要想能过方便的让任务能过 暂停和恢复,需要数据结构支持
 * @returns 
 */
function calculate(didTimeout) {
    // shouldYield如果任务没有结束,并且浏览器分配的时间片(一般是4ms)已经到期了,就会放弃本任务的执行,
    // 把线程的资源交还给浏览器,让浏览器执行更高优先级的工作,比如页面绘制,响应用户输入
    for (; i < 1000000 && (!shouldYield() || didTimeout); i++) {
        result += 1;
    }
    // 当推出本任务的时候,如果任务没有完成,返回任务函数本身,如果任务完成了就返回null
    if (i < 1000000) {
        return calculate;
    } else {
        console.log(result);
        return null;
    }
}
function calculate2(didTimeout) {
    for (; i2 < 2000000 && (!shouldYield() || didTimeout); i2++) {
        result2 += 1;
    }
    if (i2 < 2000000) {
        return calculate2;
    } else {
        console.log(result2);
        return null;
    }
}

function calculate3(didTimeout) {
    for (; i3 < 1000000 && (!shouldYield() || didTimeout); i3++) {
        result3 += 1;
    }
    if (i3 < 1000000) {
        return calculate3;
    } else {
        console.log("result3", result3);
        return null;
    }
}
// 希望能过插队,后来的任务先执行
scheduleCallback(ImmediatePriority, calculate); // -1
scheduleCallback(LowPriority, calculate2); // 10000ms
scheduleCallback(UserBlockingPriority, calculate3); // 250ms

1647834138697-37e3bfce-50a3-4f88-8ff6-89e06218b110.png

实现延迟任务

有些任务我们不想立刻开始,那我们应该怎么做呢?

  1. 回到我的Scheduler模块,修改我们的scheduleCallback,多传一个options,对我的startTime先不赋值,判断我们options中是否存在delay字段,如果存在的话,开始时间=当前时间+延迟时间,否则就是开始时间等于当前时间,也就是立刻开始。如果我们的任务开始时间大于我们的当前时间,我们还需要另一个队列timerQueue来存储尚未开始的队列。将我们的延迟任务放入我们尚未开始的队列里面,堆里存储的数据结构sortIndex此时为任务开始的时间。每当我们taskQueue队列里没有任务的时候,我们就会去timerQueue队列拿出任务放到taskQueue中。
// scheduler/src/Scheduler.js
// 尚未开始的任务队列
let timerQueue = [];
function scheduleCallback (priorityLevel, callback, options) {
    // 获取当前时间
    let currentTime = getCurrentTime();
    // 此任务的开始时间
    let startTime;
    if (typeof options === 'object' && options !== null) {
        let delay = options.delay;
        // 如果delay是一个数字,那么开始时间等于当前时间+延迟时间
        if (typeof delay === 'number' && delay > 0) {
            startTime = currentTime + delay;
        } else {
            // 否者就是开始时间等于当前时间,也就是立刻开始
            startTime = currentTime;
        }
    } else {
      	startTime = currentTime;
    }
    // 计算超时时间
    let timeout;
    switch (priorityLevel) {
        case ImmediatePriority: 
            timeout = IMMEDIATE_PRIORITY_TIMEOUT; 
            break;
        case UserBlockingPriority: 
            timeout = USER_BLOCKING_TIMEOUT; 
            break;
        case NormalPriority: 
            timeout = NORMAL_PRIORITY_TIMEOUT; 
            break;
        case LowPriority: 
            timeout = LOW_PRIORITY_TIMEOUT; 
            break;
        case IdlePriority: 
            timeout = IDLE_PRIORITY_TIMEOUT; 
            break;
    }
    // 计算一个过期时间 = 当前时间 + 超时时间
    let expirationTime = startTime + timeout;
    let newTask = {
        id: taskIdCounter++, // 每一个任务都有一个自增的id
        callback, // 真正要执行的函数
        priorityLevel, // 优先级保存下来
        expirationTime, // 过期时间
        startTime, // 任务开始的时间
        sortIndex: -1 // 排序值
    }
    // 如果说任务开始时间大于当前时间,说明此任务不需要立刻开始,需要等待一段时间后才开始
    if (startTime > currentTime) {
        // 如果是延迟任务,那么在timerQueue中的排序依赖就是开始时间了
        newTask.sortIndex = startTime;
        // 添加到延迟任务最小堆里,优先队列里
        push(timerQueue, newTask);
        // 如果现在开始队列里已经为空了,并且新添加的这个延迟任务是延迟任务队列优先级最高的那个任务
        if(peek(taskQueue) === null && newTask === peek(timerQueue)) {
            // 开启一个定时器,等到此任务的开始时间到达的时候检查延迟任务并添加到taskQueue中
            setTimeout(() => handleTimeout(currentTime), startTime - currentTime);
        }
    } else {
        // 任务在最小堆里的排序依赖就是过期时间
        newTask.sortIndex = expirationTime;
        // 向最小堆里添加一个新的任务,先比较优先级(索引)再比id
        push(taskQueue, newTask);
        // taskQueue.push(callback);
        requestHostCallback(flushWork);
    }
}

/**
 * 处理延迟任务
 * 负责把延迟队列中那些已经到达开始时间的任务从延迟队列中取出来,添加到taskQueue中执行
 */
function handleTimeout(currentTime) {
    advanceTimes(currentTime);
    if (peek(taskQueue) !== null) {
        // 如果任务队列里有任务,就再次调度一个flushWork,它会调用workLoop开始循环去清空任务队列
        requestHostCallback(flushWork);
    } else {
        // 从延迟队列中去第一个任务,也就是最早开始的那个任务
        const firstTimer = peek(timerQueue);
        if (firstTimer) {
            setTimeout(() => handleTimeout(currentTime), firstTimer.startTime - currentTime);
        }
    }
}

function advanceTimes(currentTime) {
    // 取出延迟队列顶部的任务,也就是最早开始的那个任务
    let timer = peek(timerQueue);
    while (timer) {
        if (timer.callback === null) {
            pop(timerQueue);
            // 如果此延迟任务的开始时间小于等于当前时间,说明这个任务应该开始了
        } else if (timer.startTime <= currentTime) {
            pop(timerQueue);
            // 在任务队列中排序的依据是过期时间
            timer.sortIndex = timer.expirationTime;
            push(taskQueue, timer);
        } else {
            // 如果说没有到此任务的开始时间可以直接返回了
            return;
        }
        timer = peek(timerQueue);
    }
}

修改我们workLoop的返回值

// scheduler/src/Scheduler.js
/**
 * 在这里有两个打断或者停止执行
 * 在执行每一个任务的时候,如果时间片到期了会退出workLoop
 * 另一个是在执行currentTask的时候,如果时间片到期了,也会退出执行
 * @returns 
 */
function workLoop(currentTime) {
   // ...
    if (currentTask) {
        return true;
    } else {
        // 说明taskQueue已经空了
        const firstTimer = peek(timerQueue);
        if (firstTimer) {
             setTimeout(() => handleTimeout(currentTime), firstTimer.startTime - currentTime);
        }
        return false;
    }
}
  1. 在源码里面不是直接使用的setTimeout,而是对setTimeout做了一层封装,在这里我们在SchedulerHostConfig.js文件中导出requestHostTimeout
// scheduler/src/SchedulerHostConfig.js
// ...
let taskTimeoutId;
// ...
export function requestHostTimeout(callback, ms) {
    taskTimeoutId = setTimeout(() => {
        callback(getCurrentTime())
    }, ms)
}
  1. 然后将Scheduler.js里的setTimeout全部换成requestHostTimeout
// scheduler/src/Scheduler.js
// ...
function scheduleCallback (priorityLevel, callback, options) {
    // ...
    if (startTime > currentTime) {
        // ...
        if(peek(taskQueue) === null && newTask === peek(timerQueue)) {
            // 开启一个定时器,等到此任务的开始时间到达的时候检查延迟任务并添加到taskQueue中
            requestHostTimeout(handleTimeout, startTime - currentTime);
        }
    } else {
        // ...
    }
}

/**
 * 处理延迟任务
 * 负责把延迟队列中那些已经到达开始时间的任务从延迟队列中取出来,添加到taskQueue中执行
 */
function handleTimeout(currentTime) {
    // ...
    if (peek(taskQueue) !== null) {
        // ...
    } else {
        // ...
        if (firstTimer) {
            requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
    }
}



function workLoop(currentTime) {
    // ...
        if (firstTimer) {
            requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
        // ...
    }
}
// ...
  1. 最后修改我们的index.js文件查看结果
// index.js
import { 
    scheduleCallback, // 调度回调,计划执行回调
    shouldYield, // 应该放弃执行权/中断
    ImmediatePriority, 
    UserBlockingPriority, 
    NormalPriority, 
    LowPriority, 
    IdlePriority,
 } from './scheduler';
 let result = 0, result2 = 0, result3 = 0;
 let i = 0, i2 = 0, i3= 0;
/**
 * 要想能过方便的让任务能过 暂停和恢复,需要数据结构支持
 * @returns 
 */
function calculate(didTimeout) {
    console.log("开始calculate1")
    // shouldYield如果任务没有结束,并且浏览器分配的时间片(一般是4ms)已经到期了,就会放弃本任务的执行,
    // 把线程的资源交还给浏览器,让浏览器执行更高优先级的工作,比如页面绘制,响应用户输入
    for (; i < 10000 && (!shouldYield() || didTimeout); i++) {
        result += 1;
    }
    // 当推出本任务的时候,如果任务没有完成,返回任务函数本身,如果任务完成了就返回null
    if (i < 10000) {
        return calculate;
    } else {
        console.log(result);
        return null;
    }
}
function calculate2(didTimeout) {
    console.log("开始calculate2")
    for (; i2 < 2000000 && (!shouldYield() || didTimeout); i2++) {
        result2 += 1;
    }
    if (i2 < 2000000) {
        return calculate2;
    } else {
        console.log(result2);
        return null;
    }
}

function calculate3(didTimeout) {
    console.log("开始calculate3")
    for (; i3 < 1000000 && (!shouldYield() || didTimeout); i3++) {
        result3 += 1;
    }
    if (i3 < 1000000) {
        return calculate3;
    } else {
        console.log("result3", result3);
        return null;
    }
}
// 希望能过插队,后来的任务先执行
scheduleCallback(ImmediatePriority, calculate); // -1
scheduleCallback(LowPriority, calculate2, { delay: 10000}); // 10000ms
scheduleCallback(UserBlockingPriority, calculate3); // 250ms

1647850411740-7bdc8724-0420-4057-9b41-9b89dbf1d706.png

取消任务

  1. 在index.js用task变量将我们的调度函数存储起来
// index.js
const task = scheduleCallback(LowPriority, calculate2, { delay: 10000}); // 10000ms
  1. 并引入cancelCallback方法,调用我的cancelCallback方法,将我们的task传进去就可以取消。
// index.js
import { 
    scheduleCallback, // 调度回调,计划执行回调
    shouldYield, // 应该放弃执行权/中断
    ImmediatePriority, 
    UserBlockingPriority, 
    NormalPriority, 
    LowPriority, 
    IdlePriority,
    cancelCallback
 } from './reactStudy/scheduler';
// ...
cancelCallback(task);
  1. 在Scheduler.js中新增一个cancelCallback的方法,并导出cancelCallback,在scheduleCallback函数中将我们的newTask返回。
// scheduler/src/Scheduler.js
function cancelCallback(task) {
    task.callback = null;
}

export {
    scheduleCallback,
    shouldYield,
    ImmediatePriority, 
    UserBlockingPriority, 
    NormalPriority, 
    LowPriority, 
    IdlePriority,
    cancelCallback
}

function scheduleCallback (priorityLevel, callback, options) {
		return newTask;
}

之后观察打印结果,可以看calculate2没有执行

源码:github.com/yujinhongMM…