1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| const schedule = require('node-schedule');
const parser = require('cron-parser');
const isAllowWorkerSchedule = !process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0';
function parserCron(cron, options) { const interval = parser.parseExpression(cron, options); const dates = new Array(5).fill('').map((i) => interval.next().toString()); console.log('parserCron:\n'); console.log(dates.join('\n')); return dates; }
function runScheduleCronStyle(cron, func) { console.log('进程process.env.NODE_APP_INSTANCE:', process.env.NODE_APP_INSTANCE); if (!isAllowWorkerSchedule) { console.log('不允许开启定时器'); return; }
console.log('开始定时器:', cron); parserCron(cron); const job = schedule.scheduleJob(cron, func); return job; }
function runAreaScheduleCronStyle({ cron, startTime, endTime }, func) { console.log('进程process.env.NODE_APP_INSTANCE:', process.env.NODE_APP_INSTANCE); if (!isAllowWorkerSchedule) { console.log('不允许开启定时器'); return; }
console.log('开始指定时间内定时器:', cron); parserCron(cron, { currentDate: startTime, endDate: endTime }); const job = schedule.scheduleJob({ rule: cron, start: startTime, end: endTime }, func); return job; }
function cancelScheduleJob(job, reschedule) { if (!isAllowWorkerSchedule) return; console.log('取消定时器'); job.cancel(reschedule); }
const job = runScheduleCronStyle('0/10 * * * * *', () => { console.log('job--:' + new Date()); });
const jobArea = runAreaScheduleCronStyle( { cron: '0/10 * * * * *', startTime: new Date('2021/07/13 16:30'), endTime: new Date('2021/07/13 16:31:20') }, () => { console.log('jobArea--:' + new Date()); } );
const job2 = runScheduleCronStyle('0/20 * * * * *', () => { console.log('job2--:' + new Date()); });
setTimeout(() => cancelScheduleJob(job), 60 * 1000);
|