cron表达式配置
scheduletask:
cron: 0/58 * * * * ?
定时任务实现类
@Data
@Component
public class ScheduleTaskServiceImpl implements SchedulingConfigurer, ScheduleTaskService {
@Value("${scheduletask.cron}")
private String cron;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() ->{
System.out.println("Current time:"+ DateUtil.date());
} , triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(cron);
return cronTrigger.nextExecutionTime(triggerContext);
});
}
@Override
public ResData<Object> updateCron(String cron) throws Exception {
this.cron=cron;
return ResData.success();
}
}
修改cron表达式接口
public interface ScheduleTaskService {
ResData<Object> updateCron(String cron) throws Exception;
}
修改cron表达式控制器
@Api(tags = "定时任务管理")
@RestController
@RequestMapping("/schedule")
@Slf4j
public class ScheduleController {
@Autowired
private ScheduleTaskService scheduleTaskService;
@ApiOperation(value = "更新定时任务", httpMethod = "POST", produces = "application/json")
@PostMapping("/updateCron")
public ResData<Object> updateCron(String cron) throws Exception {
log.info("new cron :{}", cron);
return scheduleTaskService.updateCron(cron);
}
}
启动类加上 @EnableScheduling 注解
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class SystemApplication {
public static void main(String[] args) {
SpringApplication.run(SystemApplication.class, args);
}
}