依赖版本
Spring Boot版本:1.5.18
参考文档
springboot 定时任务@Scheduled 和 异步@Async
springboot配置
Spring Schedule 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import org.slf4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.CronTask; import org.springframework.scheduling.config.IntervalTask; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.ScheduledMethodRunnable;
import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledThreadPoolExecutor;
@Configuration @EnableScheduling public class ScheduleConfigurer implements SchedulingConfigurer { private static final Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleConfigurer.class); @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor());
List<CronTask> cronTasks = taskRegistrar.getCronTaskList(); List<IntervalTask> fixedDelayTasks = taskRegistrar.getFixedDelayTaskList(); List<IntervalTask> fixedRateTasks = taskRegistrar.getFixedRateTaskList();
for (CronTask cronTask : cronTasks){ String expression = cronTask.getExpression(); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) cronTask.getRunnable(); log.info("method: {},expression: {}",runnable.getMethod(),expression); }
for (IntervalTask intervalTask : fixedDelayTasks){ ScheduledMethodRunnable runnable = (ScheduledMethodRunnable)intervalTask.getRunnable(); log.info("method: {},InitialDelay: {}",runnable.getMethod(),intervalTask.getInitialDelay()); }
for (IntervalTask intervalTask : fixedRateTasks){ long interval = intervalTask.getInterval(); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable)intervalTask.getRunnable(); log.info("method: {},Initial: {}",runnable.getMethod(),intervalTask.getInterval()); } }
@Bean(destroyMethod="shutdown") public Executor taskExecutor() { ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);
return scheduledThreadPoolExecutor; } }
|
设置定时任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import org.slf4j.Logger; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
@Component public class ScheduleOne { private static final Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleOne.class); @Scheduled(cron = "${cron.one}") public void test() { log.info("计划任务开始执行"); } }
|