SchedulingConfigurer
SchedulingConfigurer 支持配置定时任务,需要实现 configureTasks 函数,使用者根据实际业务实现。
@FunctionalInterface
public interface SchedulingConfigurer {
/**
* Callback allowing a {@link org.springframework.scheduling.TaskScheduler
* TaskScheduler} and specific {@link org.springframework.scheduling.config.Task Task}
* instances to be registered against the given the {@link ScheduledTaskRegistrar}.
* @param taskRegistrar the registrar to be configured.
*/
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}
该函数参数为 ScheduledTaskRegistrar,是一个任务调度注册器。根据源码查看类属性,ScheduledTaskRegistrar 支持多种任务。
@Nullable
// 触发器任务
private List<TriggerTask> triggerTasks;
@Nullable
定时器任务
private List<CronTask> cronTasks;
@Nullable
间隔执行任务
private List<IntervalTask> fixedRateTasks;
@Nullable
延迟执行任务
private List<IntervalTask> fixedDelayTasks;
动态修改定时任务执行周期
在入口类添加 @EnableScheduling 注解。
package com.skystep.drools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@Slf4j
@EnableScheduling
public class DroolsApplication {
public static void main(String[] args) {
SpringApplication.run(DroolsApplication.class, args);
}
}
实现 SchedulingConfigurer 接口,向任务注册器(taskRegistrar)中添加触发器(triggerTasks)。
package com.skystep.task;
import java.util.Calendar;
import javax.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Service;
@Data
@Service
@Slf4j
public class Task implements SchedulingConfigurer {
private long time;
@PostConstruct
public void init() {
time = 1000;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 向任务注册器添加触发器
taskRegistrar
.addTriggerTask(() -> log.info("任务执行:{}", Calendar.getInstance().getTime()),
triggerContext -> {
PeriodicTrigger periodicTrigger = new PeriodicTrigger(time);
// 指定下次触发的时间
return periodicTrigger.nextExecutionTime(triggerContext);
});
}
}
接下来动态修改任务执行周期。
package com.skystep.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
@Autowired
Task task;
@GetMapping("task/{time}")
public void setTaskTime(@PathVariable Long time) {
task.setTime(time);
}
}
调用接口即可动态修改任务执行周期。注意执行时间单位是 ms,每次刷新需要等上一次任务执行结束才会使用新时间周期执行。