Spring 스케줄러 목록 조회
보통 스프링 스케줄러는 어노테이션을 사용하여 스케줄을 정의한다.
1. 사용조건
메이븐이나 그래들에 spring-context 추가
2. 자바 및 xml에 스케줄링 활성화
자바 : @EnableScheduling 어노테이션을 사용하여 스케줄링 기능을 활성화
xml : <task:annotation-driven />
3. @Scheduled으로 스케줄 등록
@Scheduled(corn = "0 0 7 * * ?") //매일 오전 7시 실행
public void testSch1() throws Exception {
//내용생략
}
4. 스케줄 등록된 목록 조회용 Component
@Component
public class ScheduledMethodScanner {
@Autowired
private ApplicationContext appContext;
public List<Map<String, Object>> getScheduledMethods() {
List<Map<String, Object>> scheduleMethods = new ArrayList<>();
String[] beanNames = applicationContext.getBeanDefinitionNames();
Method[] methods = beanClass.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Scheduled.class)) {
Scheduled scheduledAnnotation = method.getAnnotation(Scheduled.class);
String cronExpression = scheduledAnnotation.cron();
// 사용자 정의 어노테이션 @ScheduledTask의 name 속성 가져오기
String taskName = "";
if (method.isAnnotationPresent(ScheduledTask.class)) {
ScheduledTask scheduledTaskAnnotation = method.getAnnotation(ScheduledTask.class);
taskName = scheduledTaskAnnotation.value();
}
Map<String, Object> methodInfo = new HashMap<>();
methodInfo.put("beanName", beanName);
methodInfo.put("methodName", method.getName());
methodInfo.put("cronExpression", cronExpression);
methodInfo.put("taskName", taskName);
// 가져온 taskName 추가
scheduledMethods.add(methodInfo);
}
}
return scheduledMethods;
}
}