Schedule module
Fastwa provides @fastwa/schedule
package, which integrates with the popular cron package. That allows you to schedule arbitrary code (methods/functions) to execute at a fixed date/time, recurring intervals, or once after a specified interval.
Installation
To begin using it, we first install required dependencies.
1npm i --save @fastwa/schedule
2npm i --save-dev @types/cron
Getting started
Once the installation process is complete, to activate job scheduling, import ScheduleModule
into the root AppModule
and run the forRoot()
static method as shown below:
1import { Module } from '@fastwa/common';
2import { ScheduleModule } from '@fastwa/schedule';
3
4@Module({
5 imports: [ScheduleModule.forRoot()],
6})
7export class AppModule {}
Declarative cron jobs
A cron job schedules an arbitrary function (method call) to run automatically. Cron jobs can run:
- Once, at a specified date/time.
- On a recurring basis; recurring jobs can run at a specified instant within a specified interval (for example, once per hour, once per week, once every 5 minutes)
Declare a cron job with the @Cron()
decorator preceding the method definition containing the code to be executed, as follows:
1import { Injectable } from '@fastwa/common';
2import { Cron, CronExpression } from '@fastwa/schedule';
3
4@Injectable()
5export class AppController {
6 @Socket()
7 socket: WASocket;
8
9 @Cron(CronExpression.EVERY_5_MINUTES)
10 handleCron() {
11 this.socket.sendMessage(remoteJid, 'Send message every 5 minutes');
12 }
13}