实现1、通过开启@EnableScheduling 及注解@Scheduled 实现定时执行任务
【完整示例】
package org.javatrip.springboottimer;import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.util.Date;@Component
@EnableScheduling
public class ScheduledTasks {// @Scheduled(cron = "*/50 * * * * ?") // 每小时执行一次@Scheduled(fixedRate = 50000, initialDelay = 5000,fixedDelay = 5000)public void executeEveryHour() {System.out.println("定时器被触发: " + new Date());}
}
有两种方式为不同场景
- 配置Cron表达式,@Scheduled(cron = “* */50 * * * ?”)
建议:直接点击在线Cron表达式生成器生成参数比较方便:https://www.matools.com/cron/
**【注意】**Cron表达式的开始执行时机,为表达式对应的,系统执行时间所对应的cron表达式时间,
如:每5分钟执行一次,当前系统时间为 10:03分,则定时器开始执行为 10:05执行
- 固定频率执行@Scheduled(fixedRate = 50000, initialDelay = 5000,fixedDelay = 5000)
该方式可以设置在系统启动后立即执行,也可延迟执行
实现2、通过开启@EnableScheduling及实现接口 SchedulingConfigurer 完成定时执行任务
完整示例
package org.javatrip.springboottimer;import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;@EnableScheduling
@Configuration
public class QuartzSchedulerTask implements SchedulingConfigurer {@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {// 设置可变定时器String cors = "0/"+getCount()+" * * * * ?";// 注册方式1taskRegistrar.addCronTask(() -> {System.out.println("SchedulingConfigurer cron task");}, cors);// 注册方式2taskRegistrar.addCronTask(new Runnable() {@Overridepublic void run() {System.out.println("SchedulingConfigurer cron task");}}, cors);}private int getCount() {int randomNumber = (int)(Math.random() * 10) + 1;return randomNumber;}
}
这场景主要可以实现 可变定时任务
【注意】 cors可以通过动态修改方式达到触发定时任务的可变时间。