React源码解析 (六) —— 调度器scheduler

314 阅读6分钟

作用

通过调度器可以根据任务的优先级,处理任务的执行顺序,并且确保在合适的时候执行调度器,在任务执行时间过长时,会进行中断,让出线程,并且在后续恢复后继续执行。

主要流程

调度器的主要流程可以看作是两个过程:

  1. 维护任务队列
  2. 消费任务队列中的任务

任务队列

scheduler包中定义了两个全局的数组用于处理队列,结构为小根堆类型

var taskQueue = [];
var timerQueue = [];

timerQueue中使用当前时间performance.now和任务延迟timeout作为排序依据,值越小优先级越高,其中不同类型的timeout定义如下:

var maxSigned31BitInt = 1073741823;

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;

taskQueue则以expirationTime作为排序依据

timerQueue中的任务延迟时间结束之后,会通过advanceTimers函数进入到taskQueue

function advanceTimers(currentTime) {
  // Check for tasks that are no longer delayed and add them to the queue.
  let timer = peek(timerQueue);
  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
      if (enableProfiling) {
        markTaskStart(timer, currentTime);
        timer.isQueued = true;
      }
    } else {
      // Remaining timers are pending.
      return;
    }
    timer = peek(timerQueue);
  }
}

taskQueue 就是等待被消费的任务队列

如何将任务加入到任务队列

主要在unstable_scheduleCallback中进行处理

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++,
    callback,
    priorityLevel,
    startTime,
    expirationTime,
    sortIndex: -1,
  };
  if (enableProfiling) {
    newTask.isQueued = false;
  }

  if (startTime > currentTime) {
    // This is a delayed task.
    newTask.sortIndex = startTime;
    push(timerQueue, newTask);
    if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
      // All tasks are delayed, and this is the task with the earliest delay.
      if (isHostTimeoutScheduled) {
        // Cancel an existing timeout.
        cancelHostTimeout();
      } else {
        isHostTimeoutScheduled = true;
      }
      // Schedule a timeout.
      requestHostTimeout(handleTimeout, startTime - currentTime);
    }
  } else {
    newTask.sortIndex = expirationTime;
    push(taskQueue, newTask);
    if (enableProfiling) {
      markTaskStart(newTask, currentTime);
      newTask.isQueued = true;
    }
    // Schedule a host callback, if needed. If we're already performing work,
    // wait until the next time we yield.
    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }

  return newTask;
}

函数接受三个参数:priorityLevel(任务的优先级),callback(要调度的回调函数),以及 options(一个可选对象,可以包含延迟执行的时间 delay)。

函数中主要执行了如下过程:

获取当前时间var currentTime = getCurrentTime(); 获取当前时间戳。

计算开始时间:根据 options 对象中的 delay 属性计算任务的开始时间 startTime。如果没有提供 delay 或者 delay 不是正数,则 startTime 等于当前时间。

确定超时时间:根据任务的 priorityLevel 确定超时时间 timeout。不同的优先级有不同的超时时间,这些超时时间定义了任务应该在何时之前执行。

计算过期时间expirationTime 是任务的开始时间加上超时时间。

创建任务对象:创建一个新的任务对象 newTask,包含任务的 ID、回调函数、优先级、开始时间、过期时间以及排序索引 sortIndex。如果启用了性能分析,则还会设置 isQueued 属性。

处理延迟任务:如果 startTime 大于当前时间,说明这是一个延迟任务。将其添加到 timerQueue 中,并根据情况设置或取消宿主超时(host timeout)。

处理非延迟任务:如果任务不是延迟的,将其添加到 taskQueue 中,并在必要时标记任务开始。如果宿主回调尚未被调度,且当前没有执行工作,则调度宿主回调以执行任务。

返回任务对象:函数返回新创建的任务对象。

选择合适的时机调度

对于taskQueue中的任务可以看到,在任务创建之后会执行requestHostCallback,而后进入schedulePerformWorkUntilDeadline之中 这里通过不同的运行环境选择了不同的API来处理对应的宏任务

let schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
  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);
  };
}

通常情况下会选择使用MessageChannel来处理宏任务的调度

任务队列的消费

任务加入到任务队列之后可以看到requestHostCallback被执行,并传入回调函数flushWork

function flushWork(hasTimeRemaining, initialTime) {
  if (enableProfiling) {
    markSchedulerUnsuspended(initialTime);
  }

  // We'll need a host callback the next time work is scheduled.
  isHostCallbackScheduled = false;
  if (isHostTimeoutScheduled) {
    // We scheduled a timeout but it's no longer needed. Cancel it.
    isHostTimeoutScheduled = false;
    cancelHostTimeout();
  }

  isPerformingWork = true;
  const previousPriorityLevel = currentPriorityLevel;
  try {
    if (enableProfiling) {
      try {
        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);
    }
  }
}

之后performWorkUntilDeadline会执行

const performWorkUntilDeadline = () => {
  if (scheduledHostCallback !== null) {
    const currentTime = getCurrentTime();
    // Keep track of the start time so we can measure how long the main thread
    // has been blocked.
    startTime = currentTime;
    const hasTimeRemaining = true;

    // If a scheduler task throws, exit the current browser task so the
    // error can be observed.
    //
    // Intentionally not using a try-catch, since that makes some debugging
    // techniques harder. Instead, if `scheduledHostCallback` errors, then
    // `hasMoreWork` will remain true, and we'll continue the work loop.
    let hasMoreWork = true;
    try {
      hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
    } finally {
      if (hasMoreWork) {
        // If there's more work, schedule the next message event at the end
        // of the preceding one.
        schedulePerformWorkUntilDeadline();
      } else {
        isMessageLoopRunning = false;
        scheduledHostCallback = null;
      }
    }
  } else {
    isMessageLoopRunning = false;
  }
  // Yielding to the browser will give it a chance to paint, so we can
  // reset this.
  needsPaint = false;
};

进入workLoop

function workLoop(hasTimeRemaining, initialTime) {
  let currentTime = initialTime;
  advanceTimers(currentTime);
  currentTask = peek(taskQueue);
  while (
    currentTask !== null &&
    !(enableSchedulerDebugging && isSchedulerPaused)
  ) {
    if (
      currentTask.expirationTime > currentTime &&
      (!hasTimeRemaining || shouldYieldToHost())
    ) {
      // This currentTask hasn't expired, and we've reached the deadline.
      break;
    }
    const callback = currentTask.callback;
    if (typeof callback === 'function') {
      currentTask.callback = null;
      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);
  }
  // Return whether there's additional work
  if (currentTask !== null) {
    return true;
  } else {
    const firstTimer = peek(timerQueue);
    if (firstTimer !== null) {
      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
    }
    return false;
  }
}
  1. 初始化当前时间let currentTime = initialTime; 设置当前时间为初始时间。

  2. 处理任务队列advanceTimers 函数被调用将timerQueue中过期的任务放入taskQueue

  3. 获取当前任务currentTask = peek(taskQueue); 从任务队列中获取优先级最高的任务。

  4. 执行任务循环: 只要当前任务不为空,循环会持续进行。 如果当前任务的过期时间大于当前时间,并且没有剩余时间或者应该让步给主线程,为了解决渲染时间过长卡顿主线程,React中对任务的执行时间进行了限制(frameInterval),默认设置为5ms,(超时则shouldYieldToHost() 返回 true),跳出循环。 如果当前任务的回调函数是函数类型,判断任务是否过期,若没有则执行回调函数,并处理回调返回的继续执行函数(continuationCallback)。 如果回调函数执行后返回了一个函数,即在规定时间内任务没有执行完成,将其设置为当前任务的回调函数,以便后续继续执行。 如果回调函数执行后没有返回函数或者返回了 null,则从任务队列中移除当前任务。

  5. 后续处理:再次调用advanceTimers 查看timerQueue中是否有任务需要放入taskQueue。查看是否还有需要执行的任务并返回对应的布尔值。

总结

React调度器优化了任务执行流程,通过优先级排序和延迟策略,确保任务在正确的时间执行,防止长时间运行的任务阻塞UI线程。它通过taskQueuetimerQueue管理任务,使用unstable_scheduleCallback将任务加入队列,并根据优先级和延迟时间调度。任务执行由flushWorkperformWorkUntilDeadline控制,允许任务在规定时间内运行,超时则让出线程从而实现调度的效果。