jingshuiji/utils/timedCall.js
2025-06-06 15:07:26 +08:00

74 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// utils/timedCall.js
const STORAGE_KEY = 'timedCallStorage';
/**
* 初始化或重置定时任务
* @param {string} taskName 任务名称
* @param {function} callback 回调函数
* @param {number} interval 间隔时间毫秒默认5分钟
*/
// export function setupTimedTask(taskName, callback, interval = 5 * 60 * 1000) {
export function setupTimedTask(taskName, callback, interval = 5 * 60 * 1000) {
// 清除现有定时器
clearExistingTimer(taskName);
// 立即执行任务
executeTask(taskName, callback, interval);
}
/**
* 清除定时任务
* @param {string} taskName 任务名称
*/
export function clearTimedTask(taskName) {
clearExistingTimer(taskName);
// 更新存储
const storedData = wx.getStorageSync(STORAGE_KEY) || {};
delete storedData[taskName];
wx.setStorageSync(STORAGE_KEY, storedData);
}
// ========== 私有方法 ==========
// 清除现有定时器
function clearExistingTimer(taskName) {
const storedData = wx.getStorageSync(STORAGE_KEY) || {};
const taskData = storedData[taskName] || {};
if (taskData.timerId) {
clearTimeout(taskData.timerId);
}
}
// 执行任务并设置下一次执行
function executeTask(taskName, callback, interval) {
// 执行回调函数
callback();
// 记录执行时间
const now = Date.now();
// 设置下一次执行的定时器
const timerId = setTimeout(() => {
executeTask(taskName, callback, interval);
}, interval);
// 更新存储
updateStorage(taskName, {
lastExecTime: now,
timerId: timerId,
interval: interval
});
}
// 更新存储数据
function updateStorage(taskName, newData) {
const storedData = wx.getStorageSync(STORAGE_KEY) || {};
storedData[taskName] = {
...(storedData[taskName] || {}),
...newData
};
wx.setStorageSync(STORAGE_KEY, storedData);
}