스프링으로 테스크 스케쥴링 하기
1. gradle 셋팅
plugins {
id 'org.springframework.boot' version '2.3.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.awaitility:awaitility:3.1.2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
2. 스케쥴 테스크 생성
- @Scheduled : 실행하고 싶은 특정 메소드 위에 @Scheduled 어노테이션을 붙임.
- fixedRate : 호출의 시작 시간부터 메소드 호출 간격을 지정.
(fixedDelay : 호출의 완료 시간부터 메소드 호출 간격을 지정. 상세 지정을 위해 cron = "..."식을 사용할 수도 있음.)
//ScheduledTasks.java
package com.example.schedulingtasks;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
3. 스케쥴 기능 활설화
- @EnableScheduling 어노테이션은 백그라운드 태스크 실행기가 생성되도록 함. 없으면 작업 예약 기능(Scheduling)이 작동하지 않음.
package com.example.schedulingtasks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
출처 : https://spring.io/guides/gs/scheduling-tasks/