@inest/nestjs-schedule
v0.0.9
Published
基于Nestjs + bullMQ + redis实现的分布式任务调度模块
Downloads
47
Maintainers
Readme
@inest/nestjs-schedule
基于Nestjs + bullMQ + redis实现的分布式任务调度模块
说明
默认配置项:防止任务调度中产生大量的日志数据,影响redis性能。 可根据实际情况在初始化
SchedulerModule
模块时自行配置
const DEFAULT_JOB_OPTIONS = {
removeOnComplete: {
age: 3600, // 1小时
count: 10, // 保存近10条
},
removeOnFail: {
age: 7 * 24 * 3600, // 7天
count: 100, // 保存近100条
},
stackTraceLimit: 500,
};
安装
npm i @inest/nestjs-schedule
uarn add @inest/nestjs-schedule
pnpm i @inest/nestjs-schedule
使用方法
1. 导入模块
1.1. 静态导入模块
SchedulerModule.forRoot({
connection: {
host: 'xxx.xxx.xxx.xxx',
port: 6379,
password: 'xxxxxx',
db: 0,
},
prefix: 'applicationName', // 任务名前缀
} as JobOptionsWrapper);
1.2. 异步导入模块
需要通过读取配置文件的方式获取redis配置时,使用此方式
SchedulerModule.forRootAsync({
inject: [ConfigService],
useFactory: (cs: ConfigService) => {
// 调用cs服务,获取配置文件中的配置
return {
connection: {
host: 'xxx.xxx.xxx.xxx',
port: 6379,
password: 'xxxxxx',
db: 0,
},
prefix: 'applicationName', // 任务名前缀
} as JobOptionsWrapper;
},
})
2. 分布式任务调度器的使用
2.1 cron表达式
import { Injectable } from '@nestjs/common';
@Injectable()
export class TaskService {
// 每5秒中调用一次
@Schedule('*/5 * * * * ?')
task() {
console.log('helle world');
}
}
2.2 间隔调用
import { Injectable } from '@nestjs/common';
@Injectable()
export class TaskService {
// 每5秒中调用一次
@Schedule(5000) // 5000 ms
task() {
console.log('helle world');
}
}
2.3 特定条件下调用
import { Injectable } from '@nestjs/common';
@Injectable()
export class TaskService {
// 每5秒中调用一次
@Schedule('*/5 * * * * ?', () => {
// 伪代码 应对各类特定环境才执行的场景
// return getIp() === '118.88.88.88';
// return getOS() === 'Linux';
// return getApplication() === 'taskApp';
// ...
return true;
})
task() {
console.log('helle world');
}
}
更多参数配置,请参考bull文档
3. 本地(单机)任务调度器的使用
import { Injectable } from '@nestjs/common';
@Injectable()
export class TaskService {
@LocalSchedule({
cronTime: '* * * * * *',
/**
* 特定条件下调用,同上面的场景
*/
validator() {
// 伪代码 应对各类特定环境才执行的场景
// return getIp() === '118.88.88.88';
// return getOS() === 'Linux';
// return getApplication() === 'taskApp';
// ...
return true;
},
})
localTask() {
console.log('helle world');
}
}
更多参数请参考
@nestjs/schedule
文档