[NestJs] มาควบคุมเวลาด้วย Task Scheduling บน application layer กัน

Image placeholder
แวะมาทักทายกันได้


CronJob หรือ Cron + Job 

        Cron ถูกย่อมาจาก Chronograph เป็นคำเรียกของฟังก์ชันจับเวลาที่มีรากศัพท์มาจากภาษากรีก ที่พูดถึงคำนี้ก็ไม่ได้จะพามาเรียนภาษากรีกแต่อย่างใด เพียงแค่มันเป็นชื่อโปรแกรมที่อยู่ในระบบปฏิบัติการของระบบ Unix ที่สามารถออกแบบการกำหนดเวลาไว้ล่วงหน้าได้เท่านั้น

    Cron มักจะถูกนำมาใช้ประมวลผลคำสั่ง หรือ Run Script อัตโนมัติ ที่ถูกกำหนดไว้ล่วงหน้าโดยส่วนใหญ่มักจะถูกนำไปใช้ในงาน Backup file อัตโนมัติ

    หากใครที่ทำงานด้าน Backup ที่จะต้อง Operate ด้วยน่าจะคุ้นเคยกันเป็นอย่างดี ซึ่งปัจจุบันไม่ได้มีแค่ระบบปฏิบัติการเท่านั้นที่ทำ Cron ได้ มันถูกนำมาประยุกต์ในงาน Microservice หรือตัว Runtime ที่เป็นที่นิยมอย่าง NodeJs 

    NestJs เป็น Framework ตัวหนึ่งที่มี library เจ๋งๆกับงาน Backend ค่อนข้างจะครบครั้น แน่นอนว่าในบทความนี้พูดถึง Cron เป็น Cron ใน Application Layer สามารถที่จะทำงานบน RunTime ได้เลย

    ใน NestJs สำหรับ Cron จะถูกเรียกว่า Task Scheduling เวลาที่ค้นหา Cron NestJs ก็จะขึ้นมาให้รู้ว่ามันคือ สิ่งเดียวกัน

ฝากกดโฆษณา Google Ads สัก click  เพื่อเป็นกำลังใจแก่ผู้เขียนด้วยนะครับ


การติดตั้งที่ง่ายแสนง่าย



$ npm install --save @nestjs/schedule
$ npm install --save-dev @types/cron

หลังจากติดตั้งเสร็จแล้ว ให้ Import Module ไว้ที่ไฟล์ Module และ

ประกาศ ScheduleModule.forRoot() เอาไว้ใน array ของ imports


// app.module.ts
 
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';

@Module({
  imports: [
    ScheduleModule.forRoot()
  ],
})
export class AppModule {}

นำ Annotation @Cron ใส่ลงในไฟล์ app.service.ts พร้อมกับประกาศ Expression หรือ predefind ก็สามารถทำได้


// app.service.ts import
{ Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class TasksService { private readonly logger = new Logger(TasksService.name); @Cron('30 * * * * *') handleCronPattern() { this.logger.debug('Called when the current second is 30'); }
@Cron(CronExpression.EVERY_45_SECONDS) handleCronDefind() { this.logger.debug('Called every 45 seconds'); } }

ในส่วนของ CronPattern สามารถดูการตั้งเวลาได้จากตัวอย่างในตาราง

* * * * * *every second
45 * * * * *every minute, on the 45th second
0 10 * * * *every hour, at the start of the 10th minute
0 */30 9-17 * * *every 30 minutes between 9am and 5pm
0 30 11 * * 1-5Monday to Friday at 11:30am

* * * * * *
| | | | | |
| | | | | day of week
| | | | month
| | | day of month
| | hour
| minute
second (optional)


ในส่วนของ Defind Expression สามารถดูชื่อการตั้งค่าได้จาก ไฟล์ library ของ defind expression จะมี enum ให้สามารถดูได้

https://github.com/nestjs/schedule/blob/master/lib/enums/cron-expression.enum.ts


นี้คือตัวอย่างที่ได้เขียนเอาไว้เพื่อ ไป Call Api ที่ต้องการ

import { Injectable, HttpService } from '@nestjs/common';
import { Logger } from '@nestjs/common';
import { Cron, Interval, Timeout } from '@nestjs/schedule';


@Injectable()
export class AppService {
private readonly logger = new Logger(AppService.name);

getHello(): string {
return 'Hello World!';
}

constructor(private httpService: HttpService) { }

@Cron('45 * * * * *')
async handleCron34345(): Promise<any> {
this.logger.debug('Called when the second is 45');
const res = await this.httpService.get(
'http://localhost:3000/audio/test', {
validateStatus: null
})
.toPromise().then(res => res.data)
.catch(err => this.logger.error(err));

return res.data;
}

@Interval(10000)
async handleInterval() {
this.logger.debug('Called every 10 seconds');
const res = await this.httpService.get(
            'http://localhost:3000/audio/test', {
validateStatus: null
})
.toPromise().then(res => res.data)
.catch(err => this.logger.error(err));

return res.data;
}

@Timeout(5000)
async handleTimeout() {
this.logger.debug('Called once after 5 seconds');
const res = await this.httpService.get(
'http://localhost:3000/audio/test', {
validateStatus: null
})
.toPromise().then(res => res.data)
.catch(err => this.logger.error(err));

return res.data;
}

}


สั่ง Run คำสั่งที่ root project 

npm run start:dev




แวะมาทักทายกันได้
donate

Categories: Tutorial Tags: #nestjs , 5613