一、概述
用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"); } }