【Spring框架07】定时任务
思维导图
一、基于xml方式配置
1.定时任务命名空间添加
<?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">
<!-- 配置定时任务-->
<bean id="jobTask" class="com.lcy.task.jobTask"></bean>
<task:scheduled-tasks>
<task:scheduled ref="jobTask" method="job01" cron="0/2 * * * * ? "/>
<task:scheduled ref="jobTask" method="job02" cron="0/5 * * * * ? "/>
</task:scheduled-tasks>
</beans>
2.定时任务方法代码
public class jobTask {
public void job01(){
System.out.println("任务一》》》》》》……");
}
public void job02(){
System.out.println("任务二》》》》》》……");
}
}
3.定时任务配置测试
public class jobTaskTest extends TestCase {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring.xml");
}
}
二、基于注解
1.配置定时任务驱动
和之前的步骤差不多,但是需要在spring.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:annotation-driven/>
<!-- 开启bean扫描-->
<bean id="jobTest01" class="com.lcy.task.jobTest01"></bean>
</beans>
2.定时任务代码
public class jobTest01 {
@Scheduled(cron="0/2 * * * * ? ")
public void job01(){
System.out.println("任务一》》》》》》……");
}
@Scheduled(cron="0/5 * * * * ? ")
public void job02(){
System.out.println("任务二》》》》》》……");
}
}
3.编写测试类运行
public class jobTaskTest extends TestCase {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring.xml");
}
}