需求 : 服务器启动后开始定时任务而且能够注解其余依赖的相关beanhtml
1. 注解方式 ; 2 配置文件 java
注解实现方式web
1.1 自定义类DbScheduleTask spring
@Component服务器
public class DbScheduleTask{app
@AutoWiredspa
private UserService userService;.net
@AutoWiredcode
private OrderService orderService;component
@Schedule(cron="* 0/1 * * * ?")
task(){
userService.sync();
orderService.sync();
}
}
2. 配置文件方式
一、相应的web.xml没有什么变化,所以便再也不罗列。一样的,相应的java代码业务逻辑改动也不大,只是在原来的基础上去掉@Component和@Scheduled(cron = "0/5 * * * * ?")参数,也就是把这个类和方法变成一个最简单的java类和方法就能够了。
二、既然是配置文件的方式,那么改动大的天然就是pring.xml配置,把本来用注解实现的定时功能放到配置中来,改动后的配置以下:
[html] view plain copy


- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns:task="http://www.springframework.org/schema/task"
- xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- 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.1.xsd">
-
- <!-- 指定相应的包 -->
- <context:component-scan base-package="scheduleTest"/>
- <!-- 指定相应的类 -->
- <bean id="scheTest1" class="scheduleTest.ScheduleTest1"/>
-
- <!-- 指定要定时任务须要执行的业务逻辑的java类和方法 -->
- <bean id="scheTest11" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
- <property name="targetObject"> <ref local="scheTest1" /> </property>
- <property name="targetMethod">
- <!-- 要执行的方法名称 -->
- <value>schTest1</value>
- </property>
- <property name="concurrent" value="true" />
- </bean>
-
- <!--定义触发的时间 -->
- <bean id="scheTest1Cron" class="org.springframework.scheduling.quartz.CronTriggerBean">
- <property name="jobDetail">
- <ref bean="scheTest11" />
- </property>
- <property name="cronExpression">
- <value>0/5 * * * * ?</value>
- </property>
- </bean>
-
- <!--触发器 -->
- <bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="triggers">
- <list> <ref local="scheTest1Cron" /> </list>
- </property>
- </bean>
-
- </beans>