@Service
@Slf4j
public class WorkingService {
public void work(String taskName){
log.info("当前任务:"+ taskName +" 在线程"+ Thread.currentThread().getName()+"上运行");}}
1.
2.
3.
4.
5.
6.
7.
8.
使用TaskScheduler的Bean启动定时任务
@Service
public class SchedulingService {
private final TaskScheduler taskScheduler;// 可直接注入TaskScheduler的Bean
private final WorkingService workingService;//构造器注入,免@Autowired
public SchedulingService(TaskScheduler taskScheduler, WorkingService workingService){
this.taskScheduler= taskScheduler;
this.workingService= workingService;}
public void schedule(String taskName, String cronExpression){//RunnableTask不是一个Bean,不能直接注入workingService,在它的构造器直接传入
RunnableTask task = new RunnableTask(taskName,workingService);
CronTrigger cronTrigger = new CronTrigger(cronExpression);//api接受实际执行的任务,和定时启动的cron表达式
taskScheduler.schedule(task,cronTrigger);}
public void scheduleAtFixedRate(String taskName,long period){
RunnableTask task = new RunnableTask(taskName,workingService);//api接受实际执行的任务,和间隔时间
taskScheduler.scheduleAtFixedRate(task, period);}
public void scheduleWithFixedDelay(String taskName,long delay){
RunnableTask task = new RunnableTask(taskName,workingService);//api接受实际执行的任务,和延迟时间
taskScheduler.scheduleWithFixedDelay(task, delay);}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
在启动类设置动态配置
@SpringBootApplication
@EnableScheduling
public class DynamicTaskSchedulerApplication {
public static void main(String[] args){
SpringApplication.run(DynamicTaskSchedulerApplication.class, args);}
@Bean
CommandLineRunner commandLineRunner(SchedulingService schedulingService, WorkingService workingService){
return args ->{
schedulingService.schedule("指定时间任务","50 * * * * THU");
schedulingService.scheduleAtFixedRate("指定频率任务",1000);
schedulingService.scheduleWithFixedDelay("指定延迟任务",1000);};}}