이미지 삭제 스케줄링
DB
SELECT SUBSTR(PROFILE_IMG, INSTR(PROFILE_IMG, '/', -1) + 1) "rename"
FROM "MEMBER"
UNION
SELECT CAST(IMG_RENAME AS VARCHAR2(300)) "rename"
FROM "BOARD_IMG";
@Scheduled
/*
* @Scheduled
*
* * Spring에서 제공하는 스케줄러 : 시간에 따른 특정 작업(Job)의 순서를 지정하는 방법.
*
* 설정 방법
* 1) XXXAPPlication.java 파일에 @EnableScheduling 어노테이션 추가
* 2) 스케쥴링 동작을 위한 클래스 작성
*
*
* @Scheduled 속성
* - fixedDelay : 이전 작업이 끝난 시점으로 부터 고정된 시간(ms)을 설정.
* @Scheduled(fixedDelay = 10000) // 이전 작업이 끝난 후 10초 뒤에 실행
*
* - fixedRate : 이전 작업이 수행되기 시작한 시점으로 부터 고정된 시간(ms)을 설정.
* @Scheduled(fixedRate = 10000) // 이전 작업이 시작된 후 10초 뒤에 실행
*
*
*
* * cron 속성 : UNIX계열 잡 스케쥴러 표현식으로 작성 - cron="초 분 시 일 월 요일 [년도]" - 요일 : 1(SUN) ~ 7(SAT)
* ex) 2019년 9월 16일 월요일 10시 30분 20초 cron="20 30 10 16 9 2 " // 연도 생략 가능
*
*
* @Scheduled(cron = "* * * * * 30")
* @Scheduled(cron = "0 0 12 * * *")
*
*
* - 특수문자
* * : 모든 수.
* - : 두 수 사이의 값. ex) 10-15 -> 10이상 15이하
* , : 특정 값 지정. ex) 3,4,7 -> 3,4,7 지정
* / : 값의 증가. ex) 0/5 -> 0부터 시작하여 5마다
* ? : 특별한 값이 없음. (월, 요일만 해당)
* L : 마지막. (월, 요일만 해당)
* @Scheduled(cron="0 * * * * *") // 모든 0초 마다 -> 매 분마다 실행
*
*/
BoardProjectApplication.java
package edu.kh.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class BoardProjectApplication {
public static void main(String[] args) {
SpringApplication.run(BoardProjectApplication.class, args);
}
}
ImageDeleteController
@Component
@Slf4j
@PropertySource("classpath:/" + "config.properties")
@RequiredArgsConstructor
public class ImageDeleteScheduling {
private final BoardService service;
@Value("${my.profile.folder-path}")
private String profileFolderPath;
@Value("${my.board.folder-path}")
private String boardFolderPath;
@Scheduled(cron = "0,30 * * * * *")
public void scheduling() {
log.info("스케줄러 동작!");
File boardFolder = new File(boardFolderPath);
File memberFolder = new File(profileFolderPath);
File[] boardArr = boardFolder.listFiles();
File[] memberArr = memberFolder.listFiles();
File[] imageArr = new File[boardArr.length + memberArr.length];
System.arraycopy(memberArr, 0, imageArr, 0, memberArr.length);
System.arraycopy(boardArr, 0, imageArr, memberArr.length, boardArr.length);
List<File> serverImageList = Arrays.asList(imageArr);
List<String> dbImageList = service.selectDbImageList();
if (!serverImageList.isEmpty()) {
for (File serverImage : serverImageList) {
if (dbImageList.indexOf(serverImage.getName()) == -1) {
serverImage.delete();
log.info(serverImage.getName() + " 삭제");
}
}
}
}
