文章目录
一、XML配置方式
第1步、编写类
/**
* 定时计算
*/
@Component("profitScheduler")
public class ProfitScheduler {
@Autowired
private XXXService xxxService;
public void execute() {
logger.info("start 执行定时任务");
try {
xxxService.testMethod();
} catch (Exception e) {
logger.error("执行异常。{}",e);
e.printStackTrace();
}
logger.info("end 执行定时任务");
}
}
第2步、 编写spring-scheduler.xml
配置文件:
0 0/2 * * * ?
表示每2分钟执行一次
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:scheduled-tasks scheduler="scheduler" >
<task:scheduled ref="profitScheduler" method="execute" cron="0 0/2 * * * ?" />
</task:scheduled-tasks>
<task:scheduler id="scheduler" pool-size="5" />
</beans>
<task:scheduled />
参数说明:
ref
是 定时任务的类在 Spring中的beanName
method
是 要执行的方法
initial-delay
是 任务第一次被调用前的延时,单位 毫秒
fixed-delay
是 上一个调用完成后,再次调用的延时
fixed-rate
是 上一个调用开始后,再次调用的延时(不用等待上一次调用完成)
cron
是表达式,表示在什么时候进行任务调度。
第3步、引入spring-scheduler.xml
文件:
在spring.xml
中引入spring-scheduler.xml
文件:
<import resource="classpath*:spring-scheduler.xml"/>
二、注解方式
第1步:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component(“taskJob”)
public class TaskJob {
@Scheduled(cron = "0 0 3 * * ?")
public void job1() {
System.out.println(“任务进行中。。。”);
}
}
第2步:
在spring.xml
配置文件开启task:
<task:annotation-driven/>