1.告诉springboot有个定时任务
@SpringBootApplication
@MapperScan("com.test.test.mapper")
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.编写配置类
@Configuration
public class SchedulTask implements SchedulingConfigurer {
@Autowired
private CronMapper cronMapper;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(
//这里是要执行的任务
new Runnable() {
@Override
public void run() {
System.out.println(LocalDateTime.now());
}
},
//配置定时器,这里是从数据库中取的cron表达式
new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return new CronTrigger(cronMapper.getCron()).nextExecutionTime(triggerContext);
}
}
);
}
}