@@ -9,7 +9,7 @@ import { Server, Socket } from 'socket.io';
99import { RedisService } from '../common/redis/redis.service' ;
1010import { Injectable } from '@nestjs/common' ;
1111import { getRandomNickname } from '@woowa-babble/random-nickname' ;
12- import * as cron from 'node-cron ' ;
12+ import { Cron , CronExpression } from '@nestjs/schedule ' ;
1313
1414const CLIENT_KEY_PREFIX = 'socket_client:' ;
1515const CHAT_HISTORY_KEY = 'chat:history' ;
@@ -33,22 +33,13 @@ type BroadcastPayload = {
3333export class ChatGateway implements OnGatewayConnection , OnGatewayDisconnect {
3434 @WebSocketServer ( )
3535 server : Server ;
36- private cronTask : cron . ScheduledTask ;
36+ private dayInit : boolean ;
3737
3838 constructor ( private readonly redisService : RedisService ) { }
3939
40- onModuleInit ( ) {
41- this . startMidnightCron ( ) ;
42- }
43-
44- onModuleDestroy ( ) {
45- this . cronTask . stop ( ) ;
46- }
47-
48- private startMidnightCron ( ) {
49- this . cronTask = cron . schedule ( '0 0 * * *' , ( ) => {
50- this . emitMidnightMessage ( ) ;
51- } ) ;
40+ @Cron ( CronExpression . EVERY_DAY_AT_MIDNIGHT )
41+ private midnightInitializer ( ) {
42+ this . dayInit = true ;
5243 }
5344
5445 private async emitMidnightMessage ( ) {
@@ -110,6 +101,11 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
110101
111102 await this . saveMessageToRedis ( broadcastPayload ) ;
112103
104+ if ( this . dayInit ) {
105+ this . dayInit = false ;
106+ this . emitMidnightMessage ( ) ;
107+ }
108+
113109 this . server . emit ( 'message' , broadcastPayload ) ;
114110 }
115111
0 commit comments