Javascript执行定时任务

node-schedule 用于基于时间的调度,toad-scheduler 用于基于间隔的调度。

node-scheduler

Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute).

Node 6+ is supported.

使用说明:

second (0-59)
minute (0-59)
hour (0-23)
date (1-31)
month (0-11)
year
dayOfWeek (0-6) Starting with Sunday
tz

使用方法:

每个小时的第30分钟执行

1
2
3
const job = schedule.scheduleJob({minute: 30}, function(){
console.log('Time for tea!');
});

每周日下午 2:30 记录一条消息:

1
2
3
const job = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
console.log('Time for tea!');
});

toad-scheduler

In-memory TypeScript job scheduler that repeatedly executes given tasks within specified intervals of time (e. g. “each 20 seconds”). Cron syntax is also supported in case you need it.

Node.js 12+ and modern browsers are supported

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
const { ToadScheduler, SimpleIntervalJob, Task } = require('toad-scheduler')

const scheduler = new ToadScheduler()

const task = new Task('simple task', () => { counter++ })
// 指定的时间间隔(例如“每 20 秒”)内重复执行给定任务
const job = new SimpleIntervalJob({ seconds: 20, }, task)

scheduler.addSimpleIntervalJob(job)

// when stopping your app
scheduler.stop()

参考资料

https://github.com/node-schedule/node-schedule
https://github.com/kibertoad/toad-scheduler


Javascript执行定时任务
http://example.com/20231001-Javascript执行定时任务/
作者
csorz
发布于
2023年10月18日
许可协议