`
kobe学java
  • 浏览: 249902 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

spring定时器用Annotation实现

 
阅读更多

 

spring定时器用Annotation实现

0人收藏此文章, 我要收藏发表于3个月前 , 已有46次阅读 共0个评论

1.ApplicationContext.xml配置

a)、需要在xmlns里面加入:
xmlns:task="http://www.springframework.org/schema/task" 

b)、在xsi:schemaLocation中加入
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd(别忘了最后的引号)

c)、加入配置
 <context:component-scan base-package="com.netease.lee" /><!--需要扫描的包--> 
<context:annotation-config /><!--开启注解--> 
<task:annotation-driven/> <!-- 这句是重点 定时器开关-->

d)、web.xml
<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
< /listener>



2.完全注解方式

@Service
public class AnnotationQuartz {
 @Scheduled(cron="0,10,20,30,40,50 * * * * ?") //需要注意@Scheduled这个注解,它可配置多个属性:cron\fixedDelay\fixedRate
 public void test(){
  System.out.println("0.0");
 }
}

3.注解加配置方式

@Component(如果你的项目使用的是注解而不是配置文件中写bean,那么需要加上@Component,确保这个类已经注入)
public class AnnotationQuartz {
public void test()
{
System.out.println("0.0");
}
}

spring的ApplicationContext.xml中的配置:
<task:scheduled-tasks> 
<task:scheduled ref="chartsService" method="test" cron="0 0,15,30,45 * * * ?"/> 
< /task:scheduled-tasks>

4.相关文章

http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/

http://jooben.blog.51cto.com/253727/406277

 

5.实际使用情况

按如上配置之后,定时器根本就没反应,不知道哪里的问题,还是用老方法,配置方式吧

<bean id="smsSenderTimerQuarz" class="sunit.app.timer.SMSSenderTimer"/> 

<bean id="quartzSMSSender" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="smsSenderTimerQuarz"/>
</property>
<property name="targetMethod">
<value>smsSender</value>
</property>
</bean>

<bean id="quartzSMSSenderTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="quartzSMSSender"/>
</property>
<property name="cronExpression">
<value>0 0/5 * * * ?</value> 
</property>
</bean>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics