spring執行定時任務
定義一個任務是很簡單的實現TimerTask的run方法就可以了. 如下: SayHelloTask.java 1package test.timerTask;
2 3import java.util.TimerTask; 4 5public class Task extends TimerTask { 6 7 @Override 8 public void run() { 9 // TODO Auto-generated method stub 10 System.out.println("測試TimerTask : Hello !!"); 11 } 12 13} 1package test.springTimer;
2 3import java.util.TimerTask; 4 5public class Task2 extends TimerTask{ 6 public void run(){ 7 8 System.out.println("task2 is running"); 9 } 10 11 12} 13 然後是配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
測試類如下: TestApp.java package test.timerTask;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("test/timerTask/javaTimer.xml"); // ApplicationContext context2 = new ClassPathXmlApplicationContext("test/timerTask/quartzTimer.xml"); } // 只要加載配置文件就可以了, } 運行結果: task2 is running task2 is running haha,task is running haha,task is running task2 is running 使用Java中的定時器比較簡單,其提供的任務也比較簡單, 下面來看看使用quartz來執行一個複雜的任務. 1package test.timerTask;
2 3import org.quartz.JobExecutionContext; 4import org.quartz.JobExecutionException; 5import org.springframework.scheduling.quartz.QuartzJobBean; 6 7public class SayHelloTaskUsingQuartz extends QuartzJobBean { 8 9 @Override 10 protected void executeInternal(JobExecutionContext context) 11 throws JobExecutionException { 12 // TODO Auto-generated method stub 13 System.out.println("使用Quartz 認爲調度: Hello!!"); 14 } 15 16} 17 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <bean id="sayHelloJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>test.timerTask.SayHelloTaskUsingQuartz</value> </property> </bean> <!-- 關鍵在如下兩個觸發器的配置 --> <!-- 類似於Java的簡單觸發器 --> <bean id="helloTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail"> <ref bean="sayHelloJob"/> </property> <property name="startDelay"> <value>1000</value> </property> <property name="repeatInterval"> <value>3000</value> </property> </bean> <!-- 複雜觸發器 --> <bean id="helloCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="sayHelloJob"/> </property> <property name="cronExpression"> <!-- 關鍵在配置此表達式 --> <value>0 49 15 * * </value> </property> </bean> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <ref bean="helloCronTrigger"/> </property> </bean> </beans> |