緒論
最近做項目碰到了定時任務,不知道springboot中是怎麼寫的,所以查找了一些資料,發現相當簡單,記錄一下。
代碼
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 定時任務
*/
@Component
@EnableScheduling
@EnableAsync
public class MyTasks {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyTasks.class);
@Async
@Scheduled(cron = "0/8 * * * * ?")
public void task1() {
LOGGER.info("每8秒執行一次:" + new Date());
}
@Async
@Scheduled(cron = "0/10 * * * * ?")
public void task2() {
LOGGER.info("每10秒執行一次:" + new Date());
}
}
結果
真的是超級簡單,附贈在線Cron表達式生成器:http://qqe2.com/cron/index
當時自己寫錯了表達式,還不明所以。
(若有什麼錯誤,請留言指正,3Q)