스프링부트 환경에서 스케줄러 사용
- 메인 클래스에 @EnableScheduling 어노테이션 추가
@SpringBootApplication
@EnableScheduling
public class ExampleSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleSpringApplication.class, args);
}
}
- 스케줄러를 관리하는 ExampleScheduler 클래스 생성
메소드에 @Scheduled 어노테이션을 추가하면 사용이 가능하므로 cron에 5초마다 작동하게 설정
@Component
public class ExampleScheduler {
Logger logger = LoggerFactory.getLogger(getClass());
/**
* 5초마다 작동 (로컬 서버)
*/
@Scheduled(cron = "*/5 * * * * *") // @Bean에 등록한 이름을 그대로 맵핑
public void schedule1() {
logger.info("schedule1 동작하고 있음 : {}", Calendar.getInstance().getTime());
}
}
- 서버 환경에 따라 스케줄러 시간 조건을 추가하기 위한 프로퍼티, GlobalConfig 변수 설정
예) 로컬 서버에서는 5초마다, 개발 서버에서는 10초마다, 운영 서버에서는 30분마다 설정이 필요
// global-dev.properties
uploadFile.path = /app/upload/
scheduler.cron.example1 = */10 * * * * *
// global-local.properties
uploadFile.path = /home/upload/
scheduler.cron.example1 = */5 * * * * *
// global-prod.properties
uploadFile.path = /root/upload/
scheduler.cron.example1 = */20 * * * * *
public class GlobalConfig {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApplicationContext context;
@Autowired
private ResourceLoader resourceLoader;
private String uploadFilePath;
private String schedulerCronExample;
private boolean local;
private boolean dev;
private boolean prod;
@PostConstruct
public void init() {
logger.info("init");
String[] activeProfiles = context.getEnvironment().getActiveProfiles(); // 프로필(local, prod, dev)에 따라 프로퍼티 파일을 가져옴
String activeProfile = "local"; // 기본값
if (ObjectUtils.isNotEmpty(activeProfiles)) {
activeProfile = activeProfiles[0];
}
String resourcePath = String.format("classpath:globals/global-%s.properties", activeProfile);
try {
Resource resource = resourceLoader.getResource(resourcePath);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 프로퍼티 파일에 있는 uploadFile.path가 변수에 저장됨
uploadFilePath = properties.getProperty("uploadFile.path");
this.uploadFilePath = properties.getProperty("uploadFile.path");
this.schedulerCronExample1 = properties.getProperty("scheduler.cron.example1");
// local로 서버가 올라올 경우 /home/upload
this.local = activeProfile.equals("local");
// dev로 서버가 올라올 경우 /app/upload
this.dev = activeProfile.equals("dev");
// prod로 서버가 올라올 경우 /root/upload
this.prod = activeProfile.equals("prod");
} catch (Exception e) {
logger.error("e", e);
}
}
public String getUploadFilePath() {
return uploadFilePath;
}
public String getSchedulerCronExample1() {
return schedulerCronExample1;
}
public boolean isLocal() {
return local;
}
public boolean isDev() {
return dev;
}
public boolean isProd() {
return prod;
}
}
- SchedulerCronConfiguration 클래스 생성
@Autowired를 사용해 프로퍼티 내용을 가져와서 사용하며 사용할 cron을 @Bean으로 등록
@Configuration
public class SchedulerCronConfiguration {
@Autowired
private GlobalConfig config;
@Bean
public String schedulerCronExample1() {
return config.getSchedulerCronExample1();
}
}
- 위에서 @Bean에 설정된 값을 @Scheduled cron에 변경
@Component
public class ExampleScheduler {
Logger logger = LoggerFactory.getLogger(getClass());
/**
* 프로퍼티마다 초가 다르게 작동 (로컬, 개발, 운영 서버)
*/
@Scheduled(cron = "#{@schedulerCronExample1}") // @Bean에 등록한 이름을 그대로 맵핑
public void schedule1() {
logger.info("schedule1 동작하고 있음 : {}", Calendar.getInstance().getTime());
}
}
- 결과
운영 서버에서는 20초마다 작동

'Java-Spring > 자바 스프링부트 활용 웹개발 실무용' 카테고리의 다른 글
[자바 스프링부트 활용 웹개발 실무용] 파일 업로드와 썸네일 생성 (0) | 2022.08.27 |
---|---|
[자바 스프링부트 활용 웹개발 실무용] TypeHandler로 데이터 변환하기 (0) | 2022.08.20 |
[자바 스프링부트 활용 웹개발 실무용] @PostConstruct로 로컬, 개발, 운영 설정값 프로퍼티 클래스 관리 (0) | 2022.08.17 |
[자바 스프링부트 활용 웹개발 실무용] HandleMethod로 공통 로그인 체크 (0) | 2022.08.16 |
[자바 스프링부트 활용 웹개발 실무용] Mybatis를 이용한 검색, 배열 검색과 페이징 (0) | 2022.08.16 |
스프링부트 환경에서 스케줄러 사용
- 메인 클래스에 @EnableScheduling 어노테이션 추가
@SpringBootApplication
@EnableScheduling
public class ExampleSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleSpringApplication.class, args);
}
}
- 스케줄러를 관리하는 ExampleScheduler 클래스 생성
메소드에 @Scheduled 어노테이션을 추가하면 사용이 가능하므로 cron에 5초마다 작동하게 설정
@Component
public class ExampleScheduler {
Logger logger = LoggerFactory.getLogger(getClass());
/**
* 5초마다 작동 (로컬 서버)
*/
@Scheduled(cron = "*/5 * * * * *") // @Bean에 등록한 이름을 그대로 맵핑
public void schedule1() {
logger.info("schedule1 동작하고 있음 : {}", Calendar.getInstance().getTime());
}
}
- 서버 환경에 따라 스케줄러 시간 조건을 추가하기 위한 프로퍼티, GlobalConfig 변수 설정
예) 로컬 서버에서는 5초마다, 개발 서버에서는 10초마다, 운영 서버에서는 30분마다 설정이 필요
// global-dev.properties
uploadFile.path = /app/upload/
scheduler.cron.example1 = */10 * * * * *
// global-local.properties
uploadFile.path = /home/upload/
scheduler.cron.example1 = */5 * * * * *
// global-prod.properties
uploadFile.path = /root/upload/
scheduler.cron.example1 = */20 * * * * *
public class GlobalConfig {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApplicationContext context;
@Autowired
private ResourceLoader resourceLoader;
private String uploadFilePath;
private String schedulerCronExample;
private boolean local;
private boolean dev;
private boolean prod;
@PostConstruct
public void init() {
logger.info("init");
String[] activeProfiles = context.getEnvironment().getActiveProfiles(); // 프로필(local, prod, dev)에 따라 프로퍼티 파일을 가져옴
String activeProfile = "local"; // 기본값
if (ObjectUtils.isNotEmpty(activeProfiles)) {
activeProfile = activeProfiles[0];
}
String resourcePath = String.format("classpath:globals/global-%s.properties", activeProfile);
try {
Resource resource = resourceLoader.getResource(resourcePath);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 프로퍼티 파일에 있는 uploadFile.path가 변수에 저장됨
uploadFilePath = properties.getProperty("uploadFile.path");
this.uploadFilePath = properties.getProperty("uploadFile.path");
this.schedulerCronExample1 = properties.getProperty("scheduler.cron.example1");
// local로 서버가 올라올 경우 /home/upload
this.local = activeProfile.equals("local");
// dev로 서버가 올라올 경우 /app/upload
this.dev = activeProfile.equals("dev");
// prod로 서버가 올라올 경우 /root/upload
this.prod = activeProfile.equals("prod");
} catch (Exception e) {
logger.error("e", e);
}
}
public String getUploadFilePath() {
return uploadFilePath;
}
public String getSchedulerCronExample1() {
return schedulerCronExample1;
}
public boolean isLocal() {
return local;
}
public boolean isDev() {
return dev;
}
public boolean isProd() {
return prod;
}
}
- SchedulerCronConfiguration 클래스 생성
@Autowired를 사용해 프로퍼티 내용을 가져와서 사용하며 사용할 cron을 @Bean으로 등록
@Configuration
public class SchedulerCronConfiguration {
@Autowired
private GlobalConfig config;
@Bean
public String schedulerCronExample1() {
return config.getSchedulerCronExample1();
}
}
- 위에서 @Bean에 설정된 값을 @Scheduled cron에 변경
@Component
public class ExampleScheduler {
Logger logger = LoggerFactory.getLogger(getClass());
/**
* 프로퍼티마다 초가 다르게 작동 (로컬, 개발, 운영 서버)
*/
@Scheduled(cron = "#{@schedulerCronExample1}") // @Bean에 등록한 이름을 그대로 맵핑
public void schedule1() {
logger.info("schedule1 동작하고 있음 : {}", Calendar.getInstance().getTime());
}
}
- 결과
운영 서버에서는 20초마다 작동

'Java-Spring > 자바 스프링부트 활용 웹개발 실무용' 카테고리의 다른 글
[자바 스프링부트 활용 웹개발 실무용] 파일 업로드와 썸네일 생성 (0) | 2022.08.27 |
---|---|
[자바 스프링부트 활용 웹개발 실무용] TypeHandler로 데이터 변환하기 (0) | 2022.08.20 |
[자바 스프링부트 활용 웹개발 실무용] @PostConstruct로 로컬, 개발, 운영 설정값 프로퍼티 클래스 관리 (0) | 2022.08.17 |
[자바 스프링부트 활용 웹개발 실무용] HandleMethod로 공통 로그인 체크 (0) | 2022.08.16 |
[자바 스프링부트 활용 웹개발 실무용] Mybatis를 이용한 검색, 배열 검색과 페이징 (0) | 2022.08.16 |