@Service
public class CronTaskBar implements IPollableService {
@Override
public void poll() {
System.out.println("Say Bar");
@Override
public String getCronExpression() {
return "0/1 * * * * ?";
第二个任务是一个经常更换执行周期的任务,我们用一个随机数发生器来模拟它的善变:
@Service
public class CronTaskFoo implements IPollableService {
private static final Random random = new SecureRandom();
@Override
public void poll() {
System.out.println("Say Foo");
@Override
public String getCronExpression() {
return "0/" + (random.nextInt(9) + 1) + " * * * * ?";
第三个任务就厉害了,它仿佛就像一个电灯的开关,在启用和禁用中反复横跳:
@Service
public class CronTaskUnavailable implements IPollableService {
private String cronExpression = "-";
private static final Map<String, String> map = new HashMap<>();
static {
map.put("-", "0/1 * * * * ?");
map.put("0/1 * * * * ?", "-");
@Override
public void poll() {
System.out.println("Say Unavailable");
@Override
public String getCronExpression() {
return (cronExpression = map.get(cronExpression));
如果上面的步骤都做对了,日志里应该能看到类似这样的输出:
定时调度任务动态加载开始>>>>>> 定时任务[CronTaskBar]的任务表达式未发生变化,无需刷新 定时任务[CronTaskFoo]已加载,当前任务表达式为[0/6 * * * * ?] 定时任务[CronTaskUnavailable]的任务表达式配置为禁用,将被不会被调度执行 定时调度任务动态加载结束<<<<<< Say Bar Say Bar Say Foo Say Bar Say Bar Say Bar 定时调度任务动态加载开始>>>>>> 定时任务[CronTaskBar]的任务表达式未发生变化,无需刷新 定时任务[CronTaskFoo]已加载,当前任务表达式为[0/3 * * * * ?] 定时任务[CronTaskUnavailable]已加载,当前任务表达式为[0/1 * * * * ?] 定时调度任务动态加载结束<<<<<< Say Unavailable Say Bar Say Unavailable Say Bar Say Foo Say Unavailable Say Bar Say Unavailable Say Bar Say Unavailable Say Bar