BootCamp 52day

GyeongNamΒ·2024λ…„ 1μ›” 28일
0

BootCamp

λͺ©λ‘ 보기
46/49
post-thumbnail

πŸ“… 2024λ…„ 01μ›” 26일


52일차 : Spring (12)

Scheduled

  • BoardApplication
@EnableScheduling
@SpringBootApplication
public class BoardApplication {
	public static void main(String[] args) {
		SpringApplication.run(BoardApplication.class, args);
	}
}
  • PostScheduler
@Component
@Transactional
public class PostScheduler {
    private  final PostRepository postRepository;
    @Autowired
    public PostScheduler(PostRepository postRepository){
        this.postRepository = postRepository;
    }
    /*
    초 λΆ„ μ‹œκ°„ 일 μ›” μš”μΌ ν˜•νƒœλ‘œ μŠ€μΌ€μ€„λ§ μ„€μ •
    * : 맀 초(λΆ„/μ‹œ λ“±)을 의미
    νŠΉμ • 숫자 : νŠΉμ •μˆ«μžμ˜ 초(λΆ„/μ‹œ λ“±)을 의미
    0/νŠΉμ • 숫자 : νŠΉμ •μˆ«μž λ§ˆλ‹€
    ex)
    0 0 * * * *  => 맀일 0λΆ„ 0μ΄ˆμ— μŠ€μΌ€μ€„λ§ μ‹œμž‘.
    0 0/1 * * * *  =>  맀일 1λΆ„ λ§ˆλ‹€ 0μ΄ˆμ— μŠ€μΌ€μ€„λ§ μ‹œμž‘
    0/1 * * * * *  => 맀 μ΄ˆλ§ˆλ‹€
    0 0 11 * * *  => 맀일 11μ‹œμ— μŠ€μΌ€μ€„λ§
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void postScheduler(){
        System.out.println("=== μŠ€μΌ€μ€„λŸ¬ μ‹œμž‘ ===");
        Page<Post> posts = postRepository.findAllByAppointment(Pageable.unpaged(),"Y");
        for (Post p : posts.getContent()){
            LocalDateTime now = LocalDateTime.now();
            if(p.getAppointmentTime().isBefore(now) ){
                // λ”ν‹°μ±„ν‚ΉμœΌλ‘œ λ”°λ‘œ μ €μž₯ν•˜μ§€ μ•Šμ•„λ„ 됌
                p.updateAppointment(null);
            }
        }
        System.out.println("=== μŠ€μΌ€μ€„λŸ¬ 끝 ===");
    }
}

pagination

  • PostController
public String pagePostList(Model model , @PageableDefault(size = 10, sort = "updatedTime", direction = Sort.Direction.DESC) Pageable pageable){
        Page<PostListDto> postListDtoList = postService.pageFindAll(pageable);
        model.addAttribute("postList", postListDtoList);
        return "/post/post-list";
}
  • PostService
public Page<PostListDto> pageFindAll(Pageable pageable){
        Page<Post> PostList = postRepository.findAllByAppointment(pageable, null);
        Page<PostListDto> listDto = PostList.map(
                p-> new PostListDto(
                        p.getId(),
                        p.getTitle(),
                        p.getAuthor() == null ? "읡λͺ…μœ μ €" : p.getAuthor().getEmail(),
                        p.getAppointment(),
                        p.getAppointmentTime()
                    )
                );
        return listDto;
}
  • PostRepository
    Page<Post> findAllByAppointment(Pageable pageable , String appointment);

Spring μ‹€μŠ΅ github 링크

profile
503 Service Unavailable Error

0개의 λŒ“κΈ€