문제(1)
// 고용된지 1년 미만 유저는 월마다 연차 1로 바뀜
@Cron('0 0 1 * *')
async resetAnnualLeaveOfMonth() {
// 모든 유저 정보를 불러온다.
const users: User[] = await this.userRepository.find();
// 1년 미만
await this.getLessThan1yearUsers(users);
// 1년 이상
await this.getMoreThan1year(users);
}
해결방법
export class UserService implements OnModuleInit {
// onModuleInit()은 서버가 재 시작되었을 때 발생하는 함수
async onModuleInit() {
console.log('서버가 꺼졌네요. Cron을 재실행할게요.');
const one_day = new Date().getDate();
// 오늘이 1일이라면 missedJob cron 실행
if (one_day === 1 ) {
await this.resetAnnualLeaveOfMonth();
}
}
문제(2)
해결방법
// 고용된지 1년 미만 유저는 월마다 연차 1로 바뀜
@Cron('0 0 1 * *')
async resetAnnualLeaveOfMonth() {
// 모든 유저 정보를 불러온다.
const users: User[] = await this.userRepository.find();
// 1년 미만
await this.getLessThan1yearUsers(users);
// 1년 이상
await this.getMoreThan1year(users);
// redis에 저장
await this.redis.set('usedCron', '1');
}
// 매월 마지막 일에 usedCron을 0으로 바꾼다.
@Cron('0 0 L * *')
async resetUsedCron() {
// redis에 저장
await this.redis.set('usedCron', '0');
}
// onModuleInit()은 서버가 재 시작되었을 때 발생하는 함수
async onModuleInit() {
console.log('서버가 꺼졌네요. Cron을 재실행할게요.');
const one_day = new Date().getDate();
const usedCron = await this.redis.get('usedCron');
// 오늘이 1일이라면 함수 실행
// 1일이 아닌데, 함수가 실행되지 않았다면 함수 실행
if (one_day === 1 && +this.usedCron === 0) {
await this.resetAnnualLeaveOfMonth();
} else {
if (+this.usedCron === 0) {
await this.resetAnnualLeaveOfMonth();
}
}
}