一 .核心代码
@Component
@EnableScheduling
public class ScheduleService implements SchedulingConfigurer {
private String cron = "*/5 * * * * *";
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//方法1 动态使用cron表达式设置循环间隔
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
System.out.println(format.format(new Date()) + "============1111111111111111111111========="+cron);
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
//此处使用CronTrigger触发器,可动态修改cron表达式来操作循环规则,
//但是具体使用受制于cron表达式的规范,不能做到随心所欲设置循环间隔时间
CronTrigger cronTrigger = new CronTrigger(cron);
Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
return nextExecutionTime;
}
});
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public SimpleDateFormat getFormat() {
return format;
}
public void setFormat(SimpleDateFormat format) {
this.format = format;
}
}
二.调用 修改执行时间
@Autowired
private ScheduleService scheduleService;
@Override
public Boolean setOpinionRemind(String i) {
if(i.equals("1")){
scheduleService.setCron("*/20 * * * * *");
}
return null;
}