Scheduler通过任务队列和执行时机控制实现任务调度,利用setTimeout、Promise等API避免阻塞主线程,可通过任务分解、Web Workers、异步处理和并发限制优化性能,结合try...catch和Promise.catch进行错误处理,确保任务安全执行。

Scheduler的本质是在特定的时间或满足特定条件时执行任务。JS实现Scheduler,核心在于利用
setTimeout
setInterval
requestAnimationFrame
实现Scheduler的关键在于任务队列的管理和执行时机的控制。
任务队列:可以是一个数组,用于存储待执行的任务。每个任务通常包含一个函数和一个执行时间。 执行时机:Scheduler需要根据任务的执行时间,决定何时执行任务。
class Scheduler {
constructor() {
this.queue = [];
this.running = false;
}
add(task, delay = 0) {
this.queue.push({ task, delay });
if (!this.running) {
this.run();
}
}
run() {
if (this.queue.length === 0) {
this.running = false;
return;
}
this.running = true;
const { task, delay } = this.queue.shift();
setTimeout(() => {
task();
this.run(); // 递归调用,执行下一个任务
}, delay);
}
}
// 示例
const scheduler = new Scheduler();
scheduler.add(() => console.log('Task 1 executed'), 1000);
scheduler.add(() => console.log('Task 2 executed'), 500);
scheduler.add(() => console.log('Task 3 executed'), 2000);
任务阻塞主线程是Scheduler设计中需要重点考虑的问题。如果任务执行时间过长,会影响用户体验,甚至导致页面卡顿。
任务分解: 将大型任务分解成多个小任务,分批执行。这样可以避免单个任务占用主线程时间过长。例如,可以使用
requestAnimationFrame
Web Workers: 将耗时任务放到Web Workers中执行,避免阻塞主线程。Web Workers运行在独立的线程中,不会影响主线程的运行。
异步处理: 使用Promise、async/await等异步处理方式,避免同步阻塞。例如,可以使用
setTimeout
setInterval
任务优先级: 为任务设置优先级,优先执行高优先级任务。这样可以保证重要任务的及时执行。
// 使用Promise和setTimeout避免阻塞
function longRunningTask() {
return new Promise(resolve => {
setTimeout(() => {
// 模拟耗时操作
for (let i = 0; i < 100000000; i++) {
// do something
}
console.log("Long running task completed");
resolve();
}, 0);
});
}
async function runScheduler() {
console.log("Starting scheduler");
await longRunningTask();
console.log("Scheduler finished");
}
runScheduler();并发限制是指Scheduler同时执行的任务数量不能超过一个设定的最大值。这可以防止Scheduler过度占用系统资源,导致性能下降。
维护一个正在运行的任务计数器: 每次开始执行一个任务时,计数器加1;任务执行完成后,计数器减1。
在添加任务时,检查计数器是否超过最大并发数: 如果超过,则将任务放入等待队列;如果没有超过,则立即执行任务。
任务执行完成后,检查等待队列是否有任务: 如果有,则从等待队列中取出一个任务执行。
class LimitedScheduler {
constructor(limit) {
this.queue = [];
this.running = 0;
this.limit = limit;
}
add(task) {
this.queue.push(task);
this.run();
}
run() {
if (this.running < this.limit && this.queue.length > 0) {
const task = this.queue.shift();
this.running++;
const promise = task();
promise.then(() => {
this.running--;
this.run(); // 递归调用,执行下一个任务
});
}
}
}
// 示例
const limitedScheduler = new LimitedScheduler(2); // 限制并发数为2
const task = (i) => () => new Promise((resolve) => {
setTimeout(() => {
console.log(`Task ${i} executed`);
resolve();
}, Math.random() * 2000); // 模拟不同执行时间的任务
});
for (let i = 1; i <= 5; i++) {
limitedScheduler.add(task(i));
}错误处理是Scheduler设计中不可或缺的一部分。如果任务执行过程中发生错误,Scheduler需要能够捕获并处理这些错误,避免影响其他任务的执行。
try...catch: 在任务执行函数中使用
try...catch
Promise.catch: 如果任务执行函数返回一个Promise,可以使用
Promise.catch
错误处理函数: 定义一个全局的错误处理函数,用于处理Scheduler中发生的错误。
class ErrorHandlingScheduler {
constructor() {
this.queue = [];
this.running = false;
}
add(task, delay = 0) {
this.queue.push({ task, delay });
if (!this.running) {
this.run();
}
}
run() {
if (this.queue.length === 0) {
this.running = false;
return;
}
this.running = true;
const { task, delay } = this.queue.shift();
setTimeout(() => {
try {
task();
} catch (error) {
console.error("Task execution error:", error);
// 可以选择重试任务,或者记录错误日志
} finally {
this.run(); // 递归调用,执行下一个任务
}
}, delay);
}
}
// 示例
const errorHandlingScheduler = new ErrorHandlingScheduler();
errorHandlingScheduler.add(() => {
console.log('Task 1 executed');
}, 1000);
errorHandlingScheduler.add(() => {
throw new Error('Task 2 failed');
}, 500);
errorHandlingScheduler.add(() => console.log('Task 3 executed'), 2000);
以上就是JS如何实现Scheduler?调度的实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号