Springboot整合定時任務task
阿新 • • 發佈:2018-11-26
- 使用註解@EnableScheduling開啟定時任務,會自動掃描
- 定義@Component作為元件被容器掃描
- 表示式生成地址:http://cron.qqe2.com
@SpringBootApplication //掃描 mybatis mapper 包路徑 @MapperScan(basePackages = "com.imooc.mapper") //掃描 所有需要的包, 包含一些自用的工具類包 所在的路徑 @ComponentScan(basePackages= {"com.imooc", "org.n3r.idworker"}) //開啟定時任務 @EnableScheduling //開啟非同步呼叫方法 @EnableAsync public class ImoocApplication { public static void main(String[] args) { SpringApplication.run(ImoocApplication.class, args); } }
@Component public class TestTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); // 定義每過3秒執行任務 // @Scheduled(fixedRate = 3000) // @Scheduled(cron = "4-40 * * * * ?") public void reportCurrentTime() { System.out.println("現在時間:" + dateFormat.format(new Date())); } }
可以先查詢出cron語句,再在@Scheduled(cron=" ")中填上