본문 바로가기
Spring/JPA

[Spring/JPA]Spring Scheduler

by windy7271 2024. 2. 2.
728x90
반응형

스프링 스케쥴러를 사용하는 이유는

일정 시간마다 코드가 실행될 수 있게 해줄 수 있기 때문입니다.

 

예시 상황으로 만약 기본 게시판에서 예약 글 쓰기가 있다고 생각을해봅니다. 

현재 시각 11시 52분에 예약발행을 하면 글 게시판에는 보이지 않아야하고 

11시 55분이 되는 순간 포스팅이 되어야 합니다.

 

구현해보도록 하겠습니다.

 

 

 

우선 현재시각인 11시 52분에  11시 55분 예약작성을 하려고 합니다.

 

지금 날짜 이전 코드를 선택시 프론트에서 선택 할 수 없도록 Js로 설정했습니다.

 

 

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var appointmentTimeInput = document.getElementById("appointmentTime");

        appointmentTimeInput.addEventListener("input", function() {
            var selectedDateTime = new Date(this.value);
            var today = new Date();

            if (selectedDateTime < today) {
                alert("오늘 이전의 날짜와 시간을 선택할 수 없습니다.");
                this.value = "";
            }
        });
    });
</script>

 

이제 11시 55분으로 넣어봅시다.

제목 : 스케쥴러테스트

내용 : 스케줄러 테스트 11시 55분으로 넣었습니다.

 

"Y" 는 appointment 입니다. 즉 예약여부입니다.

이제 스케줄러 코드를 짜서 매 분 마다 데이터베이스를 최신화 시키도록 하겠습니다.

 

@SpringBootApplication
@EnableScheduling
public class BoardApplication {

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

}
@Component
@Transactional
public class PostScheduler {

    private final PostRepository postRepository;

    public PostScheduler(PostRepository postRepository) {
        this.postRepository = postRepository;
    }


    @Scheduled(cron = "0 0/1 * * * *")
    public void postSchedule() {
        System.out.println("--- 스케줄러시작 ---");
        Page<Post> posts = postRepository.findByAppointment("Y", Pageable.unpaged());

        String appointment = null;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
        for (Post p : posts.getContent()) {
            LocalDateTime now = LocalDateTime.now();
            if (p.getAppointmentTime().isBefore(now)) {
                p.updateAppointment(null);
            }
        }
    }
}

 

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

	Page<Post> findByAppointment(String appointment, Pageable pageable);
}

 

데이터베이스에서 예약 여부가 "Y"인 객체를 꺼내, 페이징 처리를 하지 않은 모든결과를 가져옵니다.

 

그리고 현재시간과 비교해 시간이 지나면 null로 바꿔줘 appointment를 null 로 바꿔줍니다.

 

  초 분 시간 일 월 요일  형태로 스케쥴링 설정
  *: 매 초 (분/시 등을 )의미
  특정숫자 : 특정숫자의 초(분/시) 등을 의미
  0/숫자 : 특정 숫자마다
  ex) 0 0 * * * * >> 매일 0분 0초에 스케쥴링 시작
  ex) 0 0/1 * * * * >> 매일 1분마다 0초에 스케쥴링 시작
   ex) 0 0 11 * * * >> 매일 11시에 스케쥴링

 

 

반응형

댓글