YJ의 새벽
Spring ( @Scheduled ) 본문
@Scheduled
Spring에서 제공하는 스케줄러 - 스케줄러 : 시간에 따른 특정 작업(Job)의 순서를 지정하는 방법. *
설정 방법
1) servlet-context.xml -> Namespaces 탭 -> task 체크 후 저장
2) servlet-context.xml -> Source 탭 -> <task:annotation-driven/> 추가
@Scheduled 속성
- fixedDelay : 이전 작업이 끝난 시점으로 부터 고정된 시간(ms)을 설정.
- fixedRate : 이전 작업이 수행되기 시작한 시점으로 부터 고정된 시간(ms)을 설정.
cron 속성 : UNIX계열 잡 스케쥴러 표현식으로 작성 - cron="초 분 시 일 월 요일 [년도]" - 요일 : 1(SUN) ~ 7(SAT)
ex) 2019년 9월 16일 월요일 10시 30분 20초 cron="20 30 10 16 9 2" // 연도 생략 가능
- 특수문자
* : 모든 수.
- : 두 수 사이의 값. ex) 10-15 -> 10이상 15이하
, : 특정 값 지정. ex) 3,4,7 -> 3,4,7 지정
/ : 값의 증가. ex) 0/5 -> 0부터 시작하여 5마다
? : 특별한 값이 없음. (월, 요일만 해당)
L : 마지막. (월, 요일만 해당)
* * 주의사항 - @Scheduled 어노테이션은 매개변수가 없는 메소드에만 적용 가능.
*** servlet-context.xml 파일에 추가
*** servlet-context.xml -> Namespaces task 체크.
*** Tomcat --> Overview --> Serve modules without publishing 체크 .
-- DB 에 존재하지 않지만
-- Server 에는 존재하는 이미지를 정리해보자. ( 서버에 쌓이는 이미지 주기적으로 정리 )
@Component
@Slf4j
public class ImageDeleteScheduling {
// BOARD_IMG 테이블에서는 삭제되었으나
// 서버/resources/images/board 폴더에는 존재하는
// 이미지 파일을 정시마다 삭제
// 코딩순서
// 1 ) BOARD_IMG에 존재하는 모든 이미지 목록 조회
// 2 ) /resources/images/board 폴더에 존재하는 이미지 파일목록 조회
// 3 ) 두 목록을 비교해서 일치하지않는 이미지파일 삭제
@Autowired
private BoardService service;
@Autowired
private ServletContext application ; // application scope 객체 -> 서버폴더경로 얻어오기에사용
@Scheduled( cron = "0 0 * * * * ") // 정시마다
public void serverImageDelete() {
// 1) BOARD_IMG 모든 이미지목록 조회
List<String> dbList = service.selectDBList();
// 2) /resources/images/board 폴더에 존재하는 이미지 파일목록 조회
String folderPath = application.getRealPath("/resources/images/board");
File path = new File(folderPath); // "/resources/images/board" 폴더를 참조하는 객체
File[] arr = path.listFiles(); // path가 참조하는 폴더에있는 모든파일 배열화.
List<File> serverList = Arrays.asList(arr); // arr 을 List 로 변환
// 3 ) 두 목록을 비교해서 일치하지않는 이미지파일 삭제
if ( !serverList.isEmpty() ) { // 서버에 이미지파일이 있을때 비교/삭제진행
//server: \resources\images\board\sample1.png ...
// DB : /resources/images/board/sample1.png ....
for ( File serverImage : serverList) {
String name = "/resources/images/board/"+serverImage.getName(); // 파일명만 얻어오기
if ( dbList.indexOf(name) == -1 ) {
// dbList 에는 없는데 serverList 에만 파일이 존재할경우
log.info(serverImage.getName()+" 삭제");
serverImage.delete();
}
}
log.info("-------- 서버이미지 삭제완료 ----");
}
}
}
--- 목록조회 Service
-- 목록조회 DAO
-- 목록조회 mapper.xml
--- 로그 확인
'Spring > Spring' 카테고리의 다른 글
Spring ( Web Socket ( 메시지 ) ) (0) | 2023.05.15 |
---|---|
Spring ( AOP 관점 지향 프로그래밍 ) (0) | 2023.05.12 |
Spring 19 ( 댓글 , 대댓글 삽입,수정,삭제 ) (1) | 2023.05.10 |
Spring 18 ( 게시글 삭제 ) (0) | 2023.05.09 |
Spring 17 ( 게시글 작성/수정) (0) | 2023.05.08 |