// 注入方法
AppRegistry.registerRunnable('RunableTask', TaskRun);
// 調(diào)用
AppRegistry.runApplication('RunableTask', {});
const tasks = new Map();
let currDate = Date.now();
export const TaskRun = () => {
/**
* 初始化
*/
const init = function () {
global.requestAnimationFrame(run);
};
init();
// /**
// * 執(zhí)行,每秒執(zhí)行一次
// * 保證秒級(jí)工作正確
// */
function run() {
const now = Date.now();
if (now > currDate + 1000) {
currDate = now;
tasks.forEach(item => item.preStart(now));
}
global.requestAnimationFrame(run);
}
};
/**
* 使用方法
*/
// class TrackJob extends Jobs {
// timer = 1000;
// start(now: number) {
// console.log('start======================');
// console.log('我來了', now);
// console.log('end========================');
// }
// }
// addJob('Track', TrackJob);
/**
* 基礎(chǔ)工作類
*/
export class Jobs {
name = 'base';
/**
* 下次執(zhí)行時(shí)間戳
*/
nextTime = 0;
/**
* 重載:時(shí)間間隔
*/
timer = 0;
/**
* 預(yù)啟動(dòng)
*/
preStart(now: number) {
if (this.timer < 1000) return;
if (this.nextTime > now) return;
if (this.nextTime === 0) return (this.nextTime = now + this.timer);
this.nextTime += this.timer;
this.start(now);
}
/**
* 重載:執(zhí)行一次設(shè)置的方法
*/
start(now: number) {}
}
/**
* 添加一個(gè)工作
* @param {*} name 名稱
* @param {*} time 時(shí)間
* @param {*} fn 執(zhí)行函數(shù)
*/
export const addJob = (name: string, Job: any) => tasks.set(name, new Job());
/**
* 取消任務(wù)
* @param {*} name
*/
export const cancelJob = (name: string) => tasks.delete(name);
參考:
https://juejin.cn/post/6844903605061812232