如下代码,是一个简单的通过@Scheduled注解实现的定时任务,每隔5秒执行一次。
@Component
public class SchedualDemo {
@Autowired
DateUtils dateUtils;
@Scheduled(fixedDelay = 5000)
public void say() {
System.out.println("method say: hello " + dateUtils.getCurrentTime());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
但当代码中存在多个定时任务时,定时任务之间是串行执行,这是Spring限制。
可以在spring.xml配置文件中加入
<task:annotation-driven scheduler="scheduler"/>
<task:scheduler id="scheduler" pool-size="5"/>
用于设置线程池,这样多个定时任务就可以并行执行。
如果是没有spring.xml配置文件的spring工程,可复写一个ScheduledThreadPoolExecutor的bean,即可实现定时任务的并发执行
@Configuration public class AppConfig { @Bean public ScheduledThreadPoolExecutor scheduledExecutorService() { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); return executor; } }