[TIL] 230902 @EnableScheduling 를 사용해서 30일 지난 알림 지우기

CountryGirl·2023년 9월 2일

TIL

목록 보기
56/80

알림이 너무 오래되면 쌓이게 된다......
그래서 30일이 지나면 알림이 삭제될 수 있도록 Scheduler 를 사용하기로 했다.

📌 @EnableScheduling

@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

main() 가 있는 곳에 @EnableScheduling 를 달아서 "나는 스케줄러를 사용할거야!" 라고 알려줘야한다.


📌 NotificationDeleteScheduler

public class NotificationDeleteScheduler {
    private final NotificationRepository notificationRepository;

    @Transactional
    @Scheduled(cron = "0 0 0 * * *")		// 자정
    public void autoDeleteNotificationRepository() {
        // 30일 지난 알림 자동 삭제
        notificationRepository.deleteByCreatedAtBefore(LocalDateTime.now().minusDays(30));
    }
}
  • @Scheduled(cron = "초 분 시 일 월 요일")
    ex)

    • "0 0 * * * *" = the top of every hour of every day.
    • "*/10 * * * * *" = every ten seconds.
    • "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
    • "0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
    • "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
    • "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
    • "0 0 0 25 12 ?" = every Christmas Day at midnight

  • deleteByCreatedAtBefore(): 현재시간에서 30일 전인 알림을 삭제하는 메서드


스케줄러를 사용해서 되게 쉽게 자동으로 삭제되는 것을 구현하였다.



✅ REFERENCE

spring : Class CronSequenceGenerator

profile
💻🌾시골소녀의 엉망징창 개발 성장일지🌾💻 (2023.05.23 ~)

0개의 댓글