@SpringBootApplication
@Slf4j
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
jobs.fixedDelay=5000
jobs.cron=0/5 * * * * ?
@Component
@Slf4j
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//@Scheduled(fixedDelayString = "${jobs.fixedDelay}")
@Scheduled(fixedDelayString = "2000")
public void getTask1() throws Exception{
log.info("任务1,当前时间:" + dateFormat.format(Calendar.getInstance().getTime()));
TimeUnit.SECONDS.sleep(10);
}
@Scheduled(cron = "${jobs.cron}")
public void getTask2() throws Exception{
log.info("任务2,从配置文件加载任务信息,当前时间:" + dateFormat.format(Calendar.getInstance().getTime()));
TimeUnit.SECONDS.sleep(20);
}
}
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//设定一个长度5的定时任务线程池
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
}
}