task/ 中加入ScheduleTask。@Component 將其設為Spring Bean。@Component
public class ScheduleTask{
private static final Logger log =
LoggerFactory.getLogger(ScheduleTask.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()));
}
}
SpringApplication.run 的類別)加上 @EnableScheduling。@Scheduled 的參數 ⭐⭐⭐
fixedRate、fixedDelay、cron,而這也是我在Java原生Schedule有看到的東西~某段週期是否執行至少n次、是否正確更新資料庫...。Awaitility 這個工具,使用 polling機制,主執行緒去polling背景執行排程的非同步執行緒,確認assertion是否成功,一旦成功則pass。@SpringBootTest
public class ScheduleTaskTest {
@MockitoSpyBean
public ScheduleTask scheduleTask;
@Test
public void reportCurrentTime(){
Awaitility.await()
.atMost(Durations.TEN_SECONDS)
.untilAsserted(() -> {
verify(scheduleTask, atLeast(2))
.reportCurrentTime();
});
}
本篇文章出自《每天學Java直到今年結束》Day219,大家可以到我的網站上查看~