定時任務-quartz

一、jar 包 quartz 1.5.2.jar

       參考文檔:http://www.blogjava.net/baoyaer/articles/155645.html

二、quartz實現

1.關鍵API

  • Scheduler - 與scheduler交互的主要API;
  • Job - 你通過scheduler執行任務,你的任務類需要實現的接口;
  • JobDetail - 定義Job的實例;
  • Trigger - 觸發Job的執行;
  • Calendar - 日曆指定時間點的集合,annualCalendar、monthlyCalendar、weeklyCalendar 對每年、每月、每週的定義
2.實現

    job代碼實現


 

 <span style="background-color: rgb(255, 204, 51);">定時任務實現</span>

public static void main(String[] args) 
{
	try 
	{
		 //①創建一個JobDetail實例,指定Job
		 JobDetail jobDetail = new JobDetail("job1", "jGroup1",UploadKeywordJob.class);

		 //②通過CronTrigger定義調度規則:每天幾點上傳
		 CronTrigger cronTrigger = new CronTrigger("trigger1","tGroup1");
		 cronTrigger.setCronExpression("0 0 9 ? * *");

		 //③通過SchedulerFactory獲取一個調度器實例
		 SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		 Scheduler scheduler = schedulerFactory.getScheduler();

		 //④ 註冊並進行調度
		 scheduler.scheduleJob(jobDetail, cronTrigger);

		 //⑤調度啓動
		 scheduler.start();
                //*
         }
	catch (Exception se) 
	{
		se.printStackTrace();
	}
}

注:對於上面*號處讓主線程睡眠原因沒搞清楚,試過不加正常運行


使用Calendar,排除特定日期


①法定節日是以每年爲週期的,所以使用AnnualCalendar

AnnualCalendar holidays 
= new AnnualCalendar();

②五一勞動節

Calendar laborDay 
= new GregorianCalendar();

laborDay.add(Calendar.MONTH,
5);

laborDay.add(Calendar.DATE,
1);

holidays.setDayExcluded(laborDay, 
true); ②-1:排除的日期,如果設置爲false則爲包含

③國慶節

Calendar nationalDay 
= new GregorianCalendar();

nationalDay.add(Calendar.MONTH,
10);

nationalDay.add(Calendar.DATE,
1);

holidays.setDayExcluded(nationalDay, 
true);③-1:排除該日期

scheduler.addCalendar(
"holidays", holidays, falsefalse);④向Scheduler註冊日曆


二、spring的定時任務的實現

 1.spring中的quartz

  1. <!-- Timer schedule -->  
  2.   
  3. <!--要調度的對象-->  
  4. <bean id="jobBean" class="net.xsbiz.common.MakeHtml" />  
  5. <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  6.     <property name="targetObject" ref="jobBean" />  
  7.     <property name="targetMethod" value="execute" />  
  8.     <!--將併發設置爲false-->  
  9.     <property name="concurrent" value="false" />  
  10. </bean>  
  11.   
  12. <bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  13.         <property name="jobDetail" ref="jobDetail" />  
  14.                 <!--表達式,我的是每 30 執行一次-->  
  15.                <property name="cronExpression" value="0/30 * * * * ?" />  
  16. </bean>  
  17.   
  18. <!--  總管理類如果將lazy-init='false'那麼容器啓動就會執行調度程序   -->  
  19. <bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" >  
  20.         <property name="triggers">  
  21.             <list>  
  22.                 <!--作業調度器,list下可加入其他的調度器-->  
  23.             <ref bean="trigger" />  
  24.             </list>  
  25.     </property>  
  26. </bean>  

web.xml:

Xml代碼  收藏代碼
  1.  <!-- 設置Spring的監聽,項目啓動時候初始化 -->  
  2.  <listener>  
  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  4.  </listener>  
  5.  <!-- 指定Spring配置文件的路徑 -->  
  6.  <context-param>   
  7.       <param-name>contextConfigLocation</param-name>   
  8.       <param-value>/WEB-INF/classes/applicationContext.xml</param-value>    
  9.  </context-param>   

 

MakeHtml.java :

Java代碼  收藏代碼
  1. //調用的類  
  2. public class MakeHtml {  
  3.     //調用的方法  
  4.     public void execute(){  
  5.         //需要做的事情  
  6.     }  
  7.   
  8.   
  9.          public static void main(String[] args) {  
  10.           
  11.            
  12.             System.out.println("----begin---");   
  13.   
  14.             ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");   
  15.   
  16.             // 如果配置文件中將startQuertz bean的lazy-init設置爲false 則不用實例化   
  17.   
  18.             context.getBean("startQuertz");   
  19.   
  20.             System.out.print("----end---");  
  21.             
  22.   
  23.     }  
  24.   
  25. }  
 2.spring中的spring-task

上節介紹了在Spring 中使用Quartz,本文介紹Spring3.0以後自主開發的定時任務工具,spring task,可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,而且支持註解和配置文件兩種
形式,下面將分別介紹這兩種方式。
第一種:配置文件方式
第一步:編寫作業類
即普通的pojo,如下:
Java代碼  
import org.springframework.stereotype.Service;  
@Service  
public class TaskJob {  
      
    public void job1() {  
        System.out.println(“任務進行中。。。”);  
    }  
}  
 第二步:在spring配置文件頭中添加命名空間及描述
Xml代碼  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:task="http://www.springframework.org/schema/task"   
    。。。。。。  
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
 第三步:spring配置文件中設置具體的任務
Xml代碼  
 <task:scheduled-tasks>   
        <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
</task:scheduled-tasks>  
<context:component-scan base-package=" com.gy.mytask " />  
說明:ref參數指定的即任務類,method指定的即需要運行的方法,cron及cronExpression表達式,具體寫法這裏不介紹了,詳情見上篇文章附錄。
這個配置不消多說了,spring掃描註解用的。
到這裏配置就完成了,是不是很簡單。
第二種:使用註解形式
也許我們不想每寫一個任務類還要在xml文件中配置下,我們可以使用註解@Scheduled,我們看看源文件中該註解的定義:
Java代碼  
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  
  
  public abstract long fixedDelay();  
  
  public abstract long fixedRate();  
}  
 可以看出該註解有三個方法或者叫參數,分別表示的意思是:
cron:指定cron表達式
fixedDelay:官方文檔解釋:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示從上一個任務完成開始到下一個任務開始的間隔,單位是毫秒。
fixedRate:官方文檔解釋:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即從上一個任務開始到下一個任務開始的間隔,單位是毫秒。
 
下面我來配置一下。
第一步:編寫pojo
Java代碼  
import org.springframework.scheduling.annotation.Scheduled;    
import org.springframework.stereotype.Component;  
  
@Component(“taskJob”)  
public class TaskJob {  
    @Scheduled(cron = "0 0 3 * * ?")  
    public void job1() {  
        System.out.println(“任務進行中。。。”);  
    }  
}  
 第二步:添加task相關的配置:
Xml代碼  
 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc/spring-jdbc-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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"  
    default-lazy-init="false">  
    <context:annotation-config />  
    <!—spring掃描註解的配置   -->  
    <context:component-scan base-package="com.gy.mytask" />  
      
<!—開啓這個配置,spring才能識別@Scheduled註解   -->  
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
    <task:scheduler id="qbScheduler" pool-size="10"/>  
     
說明:理論上只需要加上這句配置就可以了,這些參數都不是必須的。
 
 Ok配置完畢,當然spring task還有很多參數,我就不一一解釋了,具體參考xsd文檔http://www.springframework.org/schema/task/spring-task-3.0.xsd。
三、最後補充


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章