Spring 定时任务的实现

来源:互联网 发布:js的split 编辑:程序博客网 时间:2024/04/29 13:39

本人暂时用到的实现定时任务的方式有2种

一、注解方式实现,简单方便

1:在applicationContext.xml中加入下面的配置,

这是spring的组件扫描,保证含有定时任务的类,能被spring扫描

<context:component-scan base-package="com.test.task">

这是定时任务的配置

<task:executor id="executor" pool-size="1" /> 
<task:scheduler id="scheduler" pool-size="1" /> 
<task:annotation-driven executor="executor" scheduler="scheduler" />

定时任务类如何写

1.用@Component标注类  

2 用@Lazy(value=false)标注类(这个写也行,不写也可以。本人在做项目时,是没有写的)

3 写具体的方法

         @Scheduled(cron="0/5 * * * * *")//表示具体运行的时间
          public void testTask(){
           //具体方法
}

4.配置完成

二、配置文件的实现方式

1.实现定时任务的类,按照普通的java类来写就可以,类中的定时任务的类的方法名称写成work()就可以了

例如

  • public class TmallPriceStoreChangeFailedGetJob {
  • public void work() {
  • //具体方法实现
  • }
  •  }

2.复制一个application.xml文件,重命名为application_tmallPriceStorceChangeFailed_task.xml,在spring   配置文件中添加

  • <import resource="application_tmallPriceStorceChangeFailed"/>

3.application_tmallPriceStorceChangeFailed_task.xml文件按照以下写法

  • <!-- quartz job config begin -->
  • <bean id="tmallPriceStoreChangeFailedGetJob" class="com.shopin.third.job.TmallPriceStoreChangeFailedGetJob" />
  • <bean id="getTmallPriceStroeChangeFailed"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  • <property name="targetObject">
  • <ref bean="tmallPriceStoreChangeFailedGetJob" />
  • </property>
  • <property name="targetMethod">
  • <value>work</value>
  • </property>
  • </bean>
  • <bean id="getTmallPriceStroeChangeFailedTask" class="org.springframework.scheduling.quartz.CronTriggerBean">
  • <property name="jobDetail">
  • <ref bean="getTmallPriceStroeChangeFailed" />
  • </property>
  • <!-- cron表达式 -->
  • <property name="cronExpression">
  • <value>0 30 09 * * ?</value><!--每天9点30执行一次 -->        
  • </property>
  • </bean>
  • <!-- quertz 启动配置 -->
  • <bean id="startTmallQuertz"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  • <property name="triggers">
  • <list>
  • <ref bean="getTmallPriceStroeChangeFailedTask" />
  • </list>
  • </property>
  • </bean>

1 0
原创粉丝点击