实现了自身的cron

This commit is contained in:
Xu Chang 2023-01-08 21:13:07 +08:00
parent ec13b32b49
commit c4e49e7c2a
4 changed files with 37 additions and 0 deletions

1
lib/utils/cron.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export declare function schedule(cron: string, fn: (date: Date) => any): void;

18
lib/utils/cron.js Normal file
View File

@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.schedule = void 0;
var tslib_1 = require("tslib");
var cronjs_matcher_1 = require("@datasert/cronjs-matcher");
var dayjs_1 = tslib_1.__importDefault(require("dayjs"));
function schedule(cron, fn) {
var futureMatches = (0, cronjs_matcher_1.getFutureMatches)(cron, {
matchCount: 1,
});
var date = (0, dayjs_1.default)(futureMatches[0]);
var interval = date.diff((0, dayjs_1.default)(), 'ms');
setTimeout(function () {
fn(new Date());
schedule(cron, fn);
}, interval);
}
exports.schedule = schedule;

View File

@ -40,6 +40,7 @@
"typescript": "~4.7.4"
},
"dependencies": {
"@datasert/cronjs-matcher": "^1.2.0",
"dayjs": "^1.11.5",
"lodash": "^4.17.21",
"uuid": "^9.0.0"

17
src/utils/cron.ts Normal file
View File

@ -0,0 +1,17 @@
import { getFutureMatches } from '@datasert/cronjs-matcher';
import DayJs from 'dayjs';
export function schedule(cron: string, fn: (date: Date) => any) {
const futureMatches = getFutureMatches(cron, {
matchCount: 1,
});
const date = DayJs(futureMatches[0]);
const interval = date.diff(DayJs(), 'ms');
setTimeout(
() => {
fn(new Date());
schedule(cron, fn);
},
interval
);
}