@Scheduled
스프링 프레임워크에서 제공하는 @Scheduled 어노테이션을 사용하면 간단하게 스케줄러 기능을 구현할 수 있습니다. 이 글에서는 @Scheduled의 개념과 이를 활용한 구현 방법을 자세히 설명하겠습니다.
@Scheduled 어노테이션 개념
@Scheduled 어노테이션은 스프링의 스케줄링 작업을 간단하게 설정할 수 있게 해주는 어노테이션입니다. 주기적으로 실행되어야 하는 작업을 선언적으로 설정할 수 있으며, 다양한 스케줄링 옵션을 제공합니다.
스케줄링 옵션:
- fixedRate: 고정된 주기로 작업을 실행합니다.
- fixedDelay: 이전 작업이 끝난 후 일정 시간이 지난 뒤에 작업을 실행합니다.
- cron: 크론 표현식을 사용하여 복잡한 주기 설정을 할 수 있습니다.
@Scheduled 사용하기
1. 의존성 추가
스프링 부트 프로젝트에서는 기본적으로 스케줄링 관련 의존성이 포함되어 있습니다.
그렇지 않은 경우에는 spring-context-support 의존성을 추가해야 합니다.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
2. @EnableScheduling 어노테이션 활성화
스케줄링을 사용하려면 메인 어플리케이션 클래스에 @EnableScheduling 어노테이션을 추가해야 합니다.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling // 이 부분에 어노테이션을 추가해준다
public class ScheduledTasksApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasksApplication.class, args);
}
}
3. @Scheduled 메서드 구현
이제 @Scheduled 어노테이션을 사용하여 주기적으로 실행될 메서드를 작성할 수 있습니다.
@Override
@Scheduled(cron = "0 0/1 * * * ?") // cron으로 주기를 설정해주자
public void pingCheck() {
log.info("[PingService] Start Ping Check ...");
List<SiteModel> siteList = null;
try {
siteList = pingStore.getSiteList();
log.info("[PingService] Site ID List : " + siteList);
} catch (Exception e) {
e.printStackTrace();
}
if (siteList == null) {
log.info("[PingService] Site List is null ...");
return;
}
siteList.forEach(site -> {
try {
if (site.getVGwUrl() == null || site.getVGwUrl().equals("")) {
log.info("[PingService] Site IP is null ... : "+ site.getVGwUrl());
site.setVCommStatus("1");
pingStore.updateCommStatus(site);
return;
}
InetAddress pingCheck = InetAddress.getByName(site.getVGwUrl());
log.info("[PingService] Ping Check ... Site IP : " + site.getVGwUrl() + " Result :" +pingCheck.isReachable(2000));
if (pingCheck.isReachable(3000)) {
site.setVCommStatus("0");
pingStore.updateCommStatus(site);
} else {
site.setVCommStatus("1");
pingStore.updateCommStatus(site);
}
} catch (UnknownHostException e) {
log.error("[PingService] UnknownHost Exception ...", e);
e.printStackTrace();
} catch (IOException e) {
log.error("[PingService] IOException ...", e);
e.printStackTrace();
}
});
log.info("[PingService] End Ping Check ...");
}
위 서비스는 서버와의 네트워크 통신 서비스를 확인하는 서비스입니다.
@Scheduled 설정 옵션
스케줄링 옵션을 더 자세히 살펴보겠습니다.
- fixedRate: 작업 시작 시점 기준으로 일정 시간마다 실행됩니다. 단위는 밀리초입니다.
@Scheduled(fixedRate = 10000) // 10초마다 실행
- fixedDelay: 이전 작업이 끝난 시점 기준으로 일정 시간 후에 다음 작업이 실행됩니다. 단위는 밀리초입니다.
@Scheduled(fixedDelay = 10000) // 이전 작업 종료 후 10초 대기
- cron: 크론 표현식을 사용하여 복잡한 일정 설정이 가능합니다. 크론 표현식은 초, 분, 시, 일, 월, 요일 순으로 설정됩니다.
@Scheduled(cron = "0 0/1 * * * ?") // 매 분 0초마다 실행
크론 표현식 예시
- "0 0 * * * *": 매 정시마다 실행
- "0 0 12 * * *": 매일 정오에 실행
- "0 0 12 * * MON-FRI": 매주 월~금 정오에 실행
ⓞ 주의사항 ⓞ
1. 예외처리 : 예외처리를 하지않으면 스케쥴링이 중지될 수 있습니다. 예외처리를 잘 해줍시다.
2. 트랜잭션 관리 : 스케줄링 작업 내에서 트랜잭션이 필요한 경우, @Transactional 어노테이션을 사용할 수 있습니다.
3. 병렬 처리 : @Scheduled 는 병렬 처리가 불가능하며, 추가 설정을 더 해줘야 합니다.
'Spring' 카테고리의 다른 글
JWT 인증 필터를 왜 @Component로 등록하면 안 되는가? (0) | 2024.11.13 |
---|---|
[Spring] 스프링에서 네트워크 Ping 테스트 (0) | 2024.06.14 |
[Spring] Spring Quartz, Spring Batch, @Scheduled 개념 (0) | 2024.06.13 |
[Spring] WebFlux란 ?? (0) | 2024.03.21 |
[Spring] dependencyManagement 와 dependencies의 차이점 (0) | 2024.02.27 |