Java定時器小實例


有時候,我們需要在Java中定義一個定時器來輪詢操作,比如每隔一段時間查詢、刪除數據庫中的某些數據等,下面記錄一下一種簡單實現方式

1,首先新建一個類,類中編寫方法來實現業務操作

public class MailQuartz {


    @Autowired 
    private MailServiceImpl sendMail;
    
    @Autowired
    private TimerServiceImpl timerServiceImpl;
    
    public void Quartz(){
            String timer = getTimerStatus();
            if(!timer.equals("1")){
                System.out.println("定時器未開啟");
                return;
            }
            List<T> result = new ArrayList<T>();
            //查詢出需要發送郵件的對象
            result = timerServiceImpl.checkSendMail();
            public void deleteOldEInvoices(){
                     timerServiceImpl.deleteOldEInvoices();
                    }
    
    //讀取配置文件中的值,開啟或者關閉定時器
    public String getTimerStatus(){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
        Properties pro = new Properties();
        try {
            pro.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pro.getProperty("timer");
    }
}

                        
View Code

這里我們創建了一個類MailQuartz,然后在類中定義了兩個方法Quartz和deleteOldEInvoices,並且在這兩個方法中,我們實現了調用service處理相應的業務,ok,下面讓我們配置其觸發方式。

2,類中的方法觸發配置信息,我們寫在applicationContext.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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<!-- 定時器(發送票據開具信息給交款人) -->
    <!-- 要調用的工作類 /HebNT/src/heb/nt/service/web/mailQuartz.java -->
    <bean id="MailQuartz" class="heb.nt.service.web.MailQuartz"></bean>
    <!-- 定義調用對象和調用對象的方法 -->
    <bean id="jobtask"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 調用的類 -->
        <property name="targetObject">
            <ref bean="MailQuartz" />
        </property>
        <!-- 調用類中的方法 -->
        <property name="targetMethod">
            <value>Quartz</value>
        </property>
    </bean>
     
    <bean id="jobtask2"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 調用的類 -->
        <property name="targetObject">
            <ref bean="MailQuartz" />
        </property>
        <!-- 調用類中的方法 -->
        <property name="targetMethod">
            <value>deleteOldEInvoices</value>
        </property>
    </bean>
    <!-- 定義觸發時間-->
    <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="jobtask" />
        </property>
        <!-- cron表達式 -->
        <property name="cronExpression">
            <!-- 每三分鍾執行一次-->
            <value>0 0/5 * * * ? *</value>
        </property>
    </bean>
    <!-- 定義觸發時間-->
    <bean id="doTime2" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="jobtask2" />
        </property>
        <!-- cron表達式 -->
        <property name="cronExpression">
            <!-- 每年每月的一號0點0分0秒執行一次-->
            <value>0 0 0 1 * ? *</value>
        </property>
    </bean>
    <!-- 總管理類 如果將lazy-init='false'那么容器啟動就會執行調度程序 -->
    <bean id="startQuertz" lazy-init="false" autowire="no"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="doTime" />
                <ref bean="doTime2" />
            </list>
        </property>
    </bean>

</beans>
View Code

查看代碼,我們可以發現,需要配置我們類MailQuartz、方法Quartz和deleteOldEInvoices的相關信息,然后觸發時間的間隔,我們用corn表達式去約束,這樣,我們就可以為實現多個方法實現定時器。

3,最后呢,為了優化,由於定時器的觸發效果是,項目一啟動,定時器就會觸發,但是在測試階段或者你不想讓定時器觸發,因為他會更改你數據庫中的測試數據,那么我們就可以在方法之前讀取配置文件中的某個變量值,然后做判斷,

String timer = getTimerStatus();    //調用getTimerStatus()方法,取得配置文件中定義的控制值
   if(!timer.equals("1")){      //然后根據值來阻止定時器的運行
    System.out.println("定時器未開啟");
    return;
   }

//讀取配置文件中的值,開啟或者關閉定時器
 public String getTimerStatus(){
  InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
  Properties pro = new Properties();
  try {
   pro.load(inputStream);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return pro.getProperty("timer");  //這里的timer值就是在application.properties中定義的
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM