spring定时任务详解(多任务处理)
Posted on: 2018-03-23, Last modified: 2018-03-23,
View: 2042
在springMVC里使用spring的定时任务非常的简单,如下:
(一)在xml里加入task的命名空间
- xmlns:task="http://www.springframework.org/schema/task"
- http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
(二)启用注解驱动的定时任务
- <task:annotation-driven scheduler="myScheduler"/>
(三)配置定时任务的线程池
推荐配置线程池,若不配置多任务下会有问题。后面会详细说明单线程的问题。
- <task:scheduler id="myScheduler" pool-size="5"/>
(四)写我们的定时任务
@Scheduled注解为定时任务,cron表达式里写执行的时机
- package com.mvc.task.impl;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.concurrent.TimeUnit;
- import org.joda.time.DateTime;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import com.mvc.task.IATask;
- @Component
- public class ATask implements IATask{
- @Scheduled(cron="0/10 * * * * ? ")
- @Override
- public void aTask(){
- try {
- TimeUnit.SECONDS.sleep(20);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println(sdf.format(DateTime.now().toDate())+"*********A任务每10秒执行一次进入测试");
- }
- }
- package com.mvc.task.impl;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import org.joda.time.DateTime;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import com.mvc.task.IBTask;
- @Component
- public class BTask implements IBTask{
- @Scheduled(cron="0/5 * * * * ? ")
- @Override
- public void bTask(){
- DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println(sdf.format(DateTime.now().toDate())+"*********B任务每5秒执行一次进入测试");
- }
- }
spring的定时任务默认是单线程,多个任务执行起来时间会有问题(B任务会因为A任务执行起来需要20S而被延后20S执行),如下图所示:

当我们配置了线程池后再来看结果(多线程下,B任务再也不会因为A任务执行起来要20S而被延后了):

From: https://blog.csdn.net/qq_33556185/article/details/51852537