Spring Boot中几种定时任务
Timer类
public static void main(String[] args){
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Timer方式执行一次定时任务");
}
};
new Timer().schedule(timerTask,1,2*1000);
}
ScheduledExecutorService类
ScheduledExecutorService,是基于线程设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去并行执行
public static void main(String[] args){
ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
scheduledExecutor.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
System.out.println("ScheduledExecutorService方式执行一次定时任务");
}
}
,0,5, TimeUnit.SECONDS);
}
Quartz
-
引入quartz依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
-
配置JobDetail和Trigger
@Configuration public class QuartzConfig { @Bean public JobDetail quartzDetail(){ return JobBuilder.newJob(QuartzTest.class).withIdentity("QuartzTest").storeDurably().build(); } @Bean public SimpleTrigger quartzTrigger(){ SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10) .repeatForever(); //CronScheduleBuilder cron= CronScheduleBuilder.cronSchedule("0/10 * * * * ?"); return TriggerBuilder.newTrigger().forJob(quartzDetail()) .withIdentity("QuartzTest") .withSchedule(scheduleBuilder) .build(); } }
-
测试
public class QuartzTest extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext){ System.out.println("quartz执行一次定时任务 "); } }
Scheduled注解
-
Spring3.0以后自带的task,在启动类上使用@EnableScheduling开启定时任务支持
-
使用
@Component public class ScheduledTest { private Logger logger = LoggerFactory.getLogger(ScheduledTest.class); /** * 每3秒执行一次定时任务 */ @Scheduled(fixedRate = 3000) public void testCron(){ logger.info("Scheduled 执行一次定时任务"); } }
-
@Scheduled(initialDelay = 1000, fixedRate = 3000) 第一次延迟1秒后执行,之后按 fixedRate 的规则每 3 秒执行一次
-
@Scheduled(cron = "0/10 * * * * ? ")通过 cron 表达式定义规则