@@ -9,7 +9,7 @@ import { Server, Socket } from 'socket.io';
9
9
import { RedisService } from '../common/redis/redis.service' ;
10
10
import { Injectable } from '@nestjs/common' ;
11
11
import { getRandomNickname } from '@woowa-babble/random-nickname' ;
12
- import * as cron from 'node-cron ' ;
12
+ import { Cron , CronExpression } from '@nestjs/schedule ' ;
13
13
14
14
const CLIENT_KEY_PREFIX = 'socket_client:' ;
15
15
const CHAT_HISTORY_KEY = 'chat:history' ;
@@ -33,22 +33,13 @@ type BroadcastPayload = {
33
33
export class ChatGateway implements OnGatewayConnection , OnGatewayDisconnect {
34
34
@WebSocketServer ( )
35
35
server : Server ;
36
- private cronTask : cron . ScheduledTask ;
36
+ private dayInit : boolean ;
37
37
38
38
constructor ( private readonly redisService : RedisService ) { }
39
39
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 ;
52
43
}
53
44
54
45
private async emitMidnightMessage ( ) {
@@ -110,6 +101,11 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
110
101
111
102
await this . saveMessageToRedis ( broadcastPayload ) ;
112
103
104
+ if ( this . dayInit ) {
105
+ this . dayInit = false ;
106
+ this . emitMidnightMessage ( ) ;
107
+ }
108
+
113
109
this . server . emit ( 'message' , broadcastPayload ) ;
114
110
}
115
111
0 commit comments