一、概述
用Spring,就是為了簡單。
但是我還是要總結下java定時任務實現的幾種方式。
1.TimerTask,等於一個線程隔一段時間運行一下。
2.ScheduledExecutorService,線程池版的TimerTask。
3.Spring支持的定時任務,@Schedule注解,支持crontab表達式。
4.quartz,比較流行的任務調度工具,就是配置起來麻煩。
這里只講3、4,前兩個跟Spring沒關系,這里不講。
二、內置定時任務
2.1 Maven依賴
內置定時任務不需要額外添加依賴。
2.2 配置文件
在application.properties 中不需要額外添加下面的配置,但是可以把定時任務的crontab表達式提出來,如:
schedule.task.test=0/2 * * * * ?
2.3 配置定時任務
需要使用@EnableScheduling注解啟動定時任務,然后在需要定時執行的方法上加上@Scheduled即可:
ScheduleConfig:
package com.cff.springbootwork.schedule.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import com.cff.springbootwork.schedule.service.ScheduleService; @Configuration @EnableScheduling public class ScheduleConfig { @Autowired ScheduleService scheduleService; @Scheduled(cron = "${schedule.task.test}") public void dayJob() { scheduleService.doJob(); } }
2.4 測試的Service
package com.cff.springbootwork.schedule.service; import org.springframework.stereotype.Service; @Service public class ScheduleService { public void doJob() { System.out.println("test"); } }