java:關於Quartz定時器的使用詳解


1.在pom.xml中添加maven依賴

<!--Quartz任務調度 -->
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>

2.在classpath路徑下配置quartz-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
    default-lazy-init="false">
    <bean id="WhatJob" class="com.suriot.web.washCar.service.WhatJob" />
    <bean id="rsh_jobDetail_1"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="WhatJob" />
        </property>
        <property name="targetMethod">
            <value>execute</value><!-- 方法名稱 -->
        </property>
    </bean><!-- CronTrigger——調度觸發 使用cron表達式 -->
    <bean id="rsh_cronTrigger_1"
        class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="rsh_jobDetail_1" />
        <property name="cronExpression">
            <value>0 03 17 11 * ?</value>
            <!-- <value>0 0 0 * * ? *</value> --><!-- 每天晚上0點執行 -->
        </property>
    </bean>
    <bean id="startQuertz"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list><!-- <ref bean="rsh_simpleTrigger1" /> -->
                <ref bean="rsh_cronTrigger_1" />
            </list>
        </property>
    </bean>
</beans>

3.配置web.xml中quartz-config.xml的文件路徑

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath:quartz-config.xml</param-value>
    </context-param>

4.建立執行文件WhatJob.java

package com.suriot.web.washCar.service;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suriot.Pay.util.ExDateUtil;

@Service
public class WhatJob {

    public void execute() {
        try {
            System.out.println("執行時間 : " + ExDateUtil.ExDate() + ",執行事件:");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

上面這種事隨着項目啟動定時器自啟動的,還有一種如果是需要觸發執行的話,參考如下,需要注意的是,只能觸發一次,然后就失效了,觸發第二次這個任務會拋異常告訴你任務被占用過期了。

WahtJob.class和自啟動是有一些不一樣的,對比參考下

package com.suriot.web.washCar.service;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suriot.Pay.util.ExDateUtil;

@Service
public class WhatJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            System.out.println("執行時間 : " + ExDateUtil.ExDate() + ",執行事件:");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

 

package com.suriot.web.washCar.util;

import java.text.ParseException;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.suriot.web.washCar.service.WhatJob;

/**
 * 工作類的具體實現,即需要定時執行的“某件事”
 */
public class Quartz {

    public static void Times() throws ParseException, SchedulerException {
        // 任務名稱
        String jobName = "times";
        // 任務組
        String jobGroup = "times";

        // 構建JobDetail
        JobDetail jobDetail = JobBuilder.newJob(WhatJob.class).withIdentity(jobName, jobGroup).build();

        // 觸發名稱
        String triName = "times";
        // 出發表達式
        String triPress = "0 00 00 1 * ?";// 每月1日00:00分運行。
        // eg:"0 30 10 15 * ?" 每月15日10:30分運行。
        CronExpression express = new CronExpression(triPress);
        // 構建觸發器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triName, jobGroup).startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(express)).build();

        // 創建調度器(Scheduler)
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();

        // 注冊調度器(Scheduler)
        sched.scheduleJob(jobDetail, trigger);

        // 啟動調度器(Scheduler)
        sched.start();

    }


}

 

關於定時器要用到的cron表達式參考鏈接:http://www.what21.com/sys/view/java_java-frame_1478840380252.html,可以試着執行幾次摸索一下規律。

個人見解,首篇博文歡迎指教,如有疑問或是侵權什么的,可以郵箱留言 my130140@163.com


免責聲明!

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



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