Scheduled-Tasks
Spring内部有一个task是Spring自带的一个设定时间自动任务调度,提供了两种方式进行配置,一种是注解的方式,而另外一种就是XML配置方式了。注解方式比较简洁,XML配置方式相对而言有些繁琐,但是应用场景的不同,两者又各有优点,所以具体使用还是根据需求来划分。因为任务调度这样的需求,通常改动都是比较多的,如果用注解的方式改动就变得麻烦了,必须去重新编译。所以更多的时候我选择用XML配置的方式。
XML配置方式
一、编写测试代码
public class TestScheduledTasks {
public void taskTest() {
System.out.println("我在执行定时任务。。。。。");
}
}
二、xml配置文件
<?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.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:scheduled-tasks>
<task:scheduled ref="testScheduledTasks" method="taskTest" cron="0 45 15 * * ?"/>
</task:scheduled-tasks>
<bean id="testScheduledTasks" class="com.example.testproject.test.TestScheduledTasks"> </bean>
</beans>
说明:ref参数指定任务类,method指定需要运行的方法。
三、在spring配置文件中引入spring-task配置文件
注解方式
一、测试代码编写
@Component
public class TestScheduledTasks {
@Scheduled(cron = “0 20 15 * * ?”)
public void taskTest() {
System.out.println(“我在执行定时任务。。。。。”);
}
}
二、在spring配置文件开启task:
task:annotation-driven/
按照以上两种方式就可以简单调用spring中的scheduled-task定时任务,