相关阅读
- 为什么阿里Java规约禁止使用Java内置Executors创建线程池?
- SpringBoot 使用@Scheduled注解配置定时任务
启用 Schedule
```java import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
<a name="VaJ3R"></a>
## 添加 Scheduled
[示例代码](https://github.com/anydong/example-spring-boot/blob/master/src/main/java/com/anydong/example/springboot/task/LogTask.java)
```java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author anydong
*/
@Component
public class LogTask {
private static final Logger LOGGER = LoggerFactory.getLogger(LogTask.class);
@Scheduled(fixedDelay = 10000)
public void printDatetime() {
LOGGER.info((new Date()).toString());
}
}
并行运行多个任务
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author anydong
*/
@Configuration
@EnableScheduling
public class SchedulingConfigurerImpl implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3,
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
scheduledTaskRegistrar.setScheduler(executor);
}
}