ตัวอย่างการเขียน Spring-boot WebFlux Scheduling
pom.xml
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
...
@SpringBootApplication
@ComponentScan(basePackages = {"com.pamarin"})
public class AppStarter {
public static void main(String[] args) {
SpringApplication.run(AppStarter.class, args);
}
}
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
ประกาศ interface
public interface TaskRunner {
void run();
}
implement interface
@Slf4j
@Component
public class CleanSessionExpiredTaskRunner implements TaskRunner {
@Override
@Scheduled(fixedDelay = 1000)
public void run() {
log.debug("running...." + System.currentTimeMillis());
}
}
หรือ
@Slf4j
@Component
public class CleanTokenExpiredTaskRunner implements TaskRunner {
//cron format
//second, minute, hour, day of month, month, day(s) of week
@Override
@Scheduled(cron = "*/5 * * * * *") //every 5 seconds
public void run() {
log.debug("clean token() running...." + System.currentTimeMillis());
}
}
@Scheduled
เป็น annotation ที่บอกว่าให้ทำ scheduling ที่ method นี้fixedDelay = 1000
คือ ให้ทำทุก 1000 millisecond หรือ 1 วินาทีcron = "*/5 * * * * *"
เป็นการเขียน cron expression ให้ทำงานตามที่กำหนด เช่น ทุก 5 วินาที
cron expressions สามารถอ่านเพิ่มเติมได้ที่ A Guide To Cron Expressions
fixedDelay vs fixedRate
- fixedDelay ทำงานตามเวลาที่ตั้งไว้ เช่น ทุก 1 วินาที ทุก 5 วินาที หรือ ทุก 10 วินาที ถ้างานที่สั่งให้ทำ มันยังทำไม่เสร็จ มันจะรอให้งานั้น ๆ เสร็จก่อน แล้วจึงค่อยทำงานถัดไป
- fixedRate จะทำงานคล้าย ๆ fixedDelay แต่จะทำตามเวลาเป๊ะ ๆ เรา fixed ไว้เท่าไหร่มันก็ทำเท่านั้น ไม่รอให้งานก่อนหน้าเสร็จ มันก็ทำต่อ
cd ไปที่ root ของ project จากนั้น
$ mvn clean install
$ mvn spring-boot:run