定时任务类
springboot中使用定时任务很简单
@EnableScheduling启用定时方法,可以写在任意类上貌似,我写在配置类,主程序,任务类都可以生效 只要存在该注解,对所有**@Scheduled**都启动@Scheduled用于定时任务方法上,标明这是个定时方法@Scheduled(cron = "0/10 * * * * ?")每个10秒运行一次 更多用法见cron表达式@Scheduled(fixedRate = 2000)从启动时间开始,每个2秒运行一次@Scheduled(fixedDelay = 4000, initialDelay = 5000)从启动时间开始,延迟 5s 后间隔 4s 执行@Component@EnableScheduling@Slf4jpublic class TaskJob {@Scheduled(cron = "0/2 * * * * ?")public void job1() {log.info("【job1】开始执行:{}", DateUtil.formatDateTime(new Date()));}}
配置(可不配)
定时任务默认的最大线程数为1,默认的名称前缀为
scheduling-java方式配置
20表示最多建20个线程
Job-Thread-%d为线程名称 ,建立的线程名称都会Job-Thread-开头,如Job-Thread-1```java package com.xkcoding.task.config;
/**
- 定时任务配置,配置线程池,使用不同线程执行任务,提升效率
- *
- @author yangkai.shen
@date Created in 2018-11-22 19:02 */ @Configuration @EnableScheduling //启用定时任务 @ComponentScan(basePackages = {“com.xkcoding.task.job”}) public class TaskConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
/**
- 这里等同于配置文件配置
- {@code spring.task.scheduling.pool.size=20} - Maximum allowed number of threads.
- {@code spring.task.scheduling.thread-name-prefix=Job-Thread- } - Prefix to use for the names of newly created threads.
- {@link org.springframework.boot.autoconfigure.task.TaskSchedulingProperties} */ @Bean public Executor taskExecutor() { return new ScheduledThreadPoolExecutor(20, new BasicThreadFactory.Builder().namingPattern(“Job-Thread-%d”).build()); } }
<a name="ymXx0"></a>
## 配置文件方式配置
- 完全等价上面的配置类
```yaml
spring:
task:
scheduling:
pool:
size: 20
thread-name-prefix: Job-Thread-
