标签:
在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 * * * * ? ") //每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 * * * * ? ") //每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执行),如下图所示:
cron表达式详解:
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为标签:
原文地址:http://blog.csdn.net/qq_33556185/article/details/51852537