Files
kiss-translator/src/libs/pool.js

112 lines
2.5 KiB
JavaScript
Raw Normal View History

import { DEFAULT_FETCH_INTERVAL, DEFAULT_FETCH_LIMIT } from "../config";
2024-03-19 18:07:18 +08:00
import { kissLog } from "./log";
2023-08-20 19:27:29 +08:00
/**
* 任务池
* @param {*} fn
* @param {*} preFn
* @param {*} _interval
* @param {*} _limit
* @returns
*/
const taskPool = (_interval = 100, _limit = 100, _retryInteral = 1000) => {
2023-08-04 16:05:14 +08:00
const pool = [];
const maxRetry = 2; // 最大重试次数
let maxCount = _limit; // 最大数量
let curCount = 0; // 当前数量
let interval = _interval; // 间隔时间
2023-08-11 16:48:09 +08:00
let timer = null;
2023-08-04 16:05:14 +08:00
2023-08-11 16:48:09 +08:00
const run = async () => {
2023-08-04 16:05:14 +08:00
// console.log("timer", timer);
2023-08-11 16:48:09 +08:00
timer && clearTimeout(timer);
timer = setTimeout(run, interval);
2023-08-04 16:05:14 +08:00
if (curCount < maxCount) {
const item = pool.shift();
if (item) {
2023-10-19 14:28:18 +08:00
curCount++;
const { fn, args, resolve, reject, retry } = item;
2023-08-04 16:05:14 +08:00
try {
const res = await fn(args);
2023-10-19 14:28:18 +08:00
resolve(res);
2023-08-04 16:05:14 +08:00
} catch (err) {
2024-03-19 18:07:18 +08:00
kissLog(err, "task");
2023-10-19 14:28:18 +08:00
if (retry < maxRetry) {
const retryTimer = setTimeout(() => {
clearTimeout(retryTimer);
pool.push({ args, resolve, reject, retry: retry + 1 });
}, _retryInteral);
} else {
reject(err);
}
} finally {
curCount--;
2023-08-04 16:05:14 +08:00
}
}
}
2023-08-11 16:48:09 +08:00
};
2023-08-04 16:05:14 +08:00
return {
push: async (fn, args) => {
2023-08-11 16:48:09 +08:00
if (!timer) {
run();
}
2023-08-04 16:05:14 +08:00
return new Promise((resolve, reject) => {
pool.push({ fn, args, resolve, reject, retry: 0 });
2023-08-04 16:05:14 +08:00
});
},
2023-08-06 22:31:42 +08:00
update: (_interval = 100, _limit = 100) => {
2023-08-04 16:05:14 +08:00
if (_interval >= 0 && _interval <= 5000 && _interval !== interval) {
interval = _interval;
}
if (_limit >= 1 && _limit <= 100 && _limit !== maxCount) {
maxCount = _limit;
}
},
clear: () => {
pool.length = 0;
curCount = 0;
timer && clearTimeout(timer);
2023-08-11 16:48:09 +08:00
timer = null;
2023-08-04 16:05:14 +08:00
},
};
};
/**
* 请求池实例
*/
let fetchPool;
/**
* 获取请求池实例
*/
export const getFetchPool = (interval, limit) => {
if (!fetchPool) {
fetchPool = taskPool(
interval ?? DEFAULT_FETCH_INTERVAL,
limit ?? DEFAULT_FETCH_LIMIT
);
} else if (interval && limit) {
updateFetchPool(interval, limit);
}
return fetchPool;
};
/**
* 更新请求池参数
* @param {*} interval
* @param {*} limit
*/
export const updateFetchPool = (interval, limit) => {
fetchPool && fetchPool.update(interval, limit);
};
/**
* 清空请求池
*/
export const clearFetchPool = () => {
fetchPool && fetchPool.clear();
};