歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring3.0定時任務 (一) 簡單示例

Spring3.0定時任務 (一) 簡單示例

日期:2017/3/1 10:04:45   编辑:Linux編程

在項目中經常用到的spring的一個功能就是定時任務,它可以自動監視時間,到點就執行,給程序帶來了很大的方便,很多地方都會需要這種功能,比如做數據備份、同步等操作。最近一直比較忙,主要是比較懶,今天把這部分稍作小結。

使用spring定時任務的前提:項目中已經搭建好了spring環境(我用的是spring3.0)。

一、基本使用:

spring的定時任務使用起來十分方便,只需要兩步:1、寫好執行定時任務的類和方法;2、配置spring定時任務配置文件:

1、寫好執行定時任務的類和方法:

package com.test;

public class Test {

public void test() {
System.out.println("執行定時任務的方法。");
}
}

2、配置spring的定時任務配置文件(可以新建一個xml文件,也可以在已經有的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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

<!--必須,QuartzScheduler 延時啟動,應用啟動後 QuartzScheduler 再啟動-->
<property name="startupDelay" value="60"/>
<!-- 普通觸發器 :觸發器列表-->
<property name="triggers">
<list>
<ref local="<SPAN >testTrigger</SPAN>"/>
</list>
</property>
</bean>

<!-- 配置執行定時任務的類和方法 -->&nbsp;
<bean id="<SPAN >testDetail</SPAN>"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<bean class="<SPAN >com.test.Test</SPAN>"></bean>
</property>
<property name="targetMethod">
<value><SPAN >test</SPAN></value>
</property>
</bean>

<!-- 配置觸發器 -->&nbsp;
<bean id="<SPAN >testTrigger</SPAN>"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="<SPAN >testDetail</SPAN>"/> <!-- 觸發器觸發的 執行定時任務的bean --> &nbsp;
</property>
<property name="cronExpression">
<!-- 每天23時 --> <!-- 定時任務執行的間隔 -->
<value>0 0 23 * * ?</value>
</property>
</bean>
</beans>

二、spring定時任務的執行間隔配置、多個定時任務的配置(請點擊 http://www.linuxidc.com/Linux/2012-12/76484.htm )

Copyright © Linux教程網 All Rights Reserved