版权声明:本文为优快云博主「F·F」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_42310288/article/details/80555792
配置和使用
根据Spring的文档说明,默认采用的是单线程的模式,也就是说多个任务的执行是会相互影响的。例如,如果A任务执行时间比较长,那么B任务必须等到A任务执行完毕后才会启动执行。
第一步:在Spring.xml中开启定时器的功能
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
<!-- 让Spring找到被@Component注解的类 -->
<context:component-scan base-package="com.ff.job" />
<!--定时器开关 -->
<task:annotation-driven />
</beans>
第二步:编写定时器类
package com.ff.job;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TaskSchedulingJob {
private static final Logger LOG = Logger.getLogger(TaskSchedulingJob.class);
@Scheduled(cron = "0/5 * * * * ? ")
public void aTask() {
LOG.info("a任务每5秒执行一次,执行时间为10秒");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
}
}
@Scheduled(cron = "0/5 * * * * ? ")
public void bTask() {
LOG.info("b任务每5秒执行一次");
}
}
第三步:启动web服务器,观察结果
11:24:15[spring-job] INFO (TaskSchedulingJob.java:26) - b任务每5秒执行一次11:24:20[spring-job] INFO (TaskSchedulingJob.java:16) - a任务每5秒执行一次,执行时间为10秒11:24:30[spring-job] INFO (TaskSchedulingJob.java:26) - b任务每5秒执行一次11:24:35[spring-job] INFO (TaskSchedulingJob.java:16) - a任务每5秒执行一次,执行时间为10秒11:24:45[spring-job] INFO (TaskSchedulingJob.java:26) - b任务每5秒执行一次 结果分析:期望b任务每5秒执行一次,可由于a任务执行时间为10秒,影响了b任务的执行,只能等到下一个符合cron条件的某一个5秒时刻才开始执行。