quartz(1)基本使用

quartz:Quartz是一個徹底由Java編寫的開源任務調度的框架,經過觸發器設置做業定時運行規則,控制做業的運行時間java

一、SimpleTrigger

1.一、引入jar

<dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.2.3</version>
    </dependency>

1.二、定義任務類

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloJob implements Job{


    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //具體的業務邏輯
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("hello word"+format.format(new Date()));
    }
}

1.三、建立JobDetail,Striiger,Schedule

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
 * Created by Administrator on 2017/6/23.
 */
public class HelloScheduler {

    public static void main(String[] args) {
        //建立 jobDetail 綁定到 job
        JobDetail jobDetail= JobBuilder.newJob(HelloJob.class).withIdentity("任務名稱","任務組") .build();



        //建立trigger  啓動任務並在3秒後執行任務  而且只執行一次
        Date startTime=new Date();//任務執行時間點
        startTime.setTime(startTime.getTime()+3000);
        SimpleTrigger trigger= (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity("SimpleTrigger name","SimpleTrigger group")
                .startAt(startTime)
                .build();


        //建立 schedule 實例
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler= null;
        try {
            scheduler = schedulerFactory.getScheduler();
            scheduler.start();
            scheduler.scheduleJob(jobDetail,trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }



    }
}

二、CronTrigger

定義job任務實現類,和SimpleTrigger同樣。spring

啓動任務app

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Created by Administrator on 2017/6/23.
 * 表達式: 秒 分 時 日 月 周 年(可選)
 */
public class HelloCronScheduler {

    public static void main(String[] args) {
        //建立 jobDetail 綁定到 job
        JobDetail jobDetail= JobBuilder.newJob(HelloJob.class).withIdentity("任務名稱","任務組").build();

        //建立trigger   每兩秒執行一次jobDetail
        CronTrigger trigger= TriggerBuilder.newTrigger().withIdentity("任務觸發器name","觸發器組name")
                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?"))
                .build();

        //建立 schedule 實例
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler= null;
        try {
            scheduler = schedulerFactory.getScheduler();
            scheduler.start();
            scheduler.scheduleJob(jobDetail,trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }



    }
}

三、集成到spring

3.一、引入jar

<quartz.version>2.2.3</quartz.version>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>${quartz.version}</version>
</dependency>

3.二、定義任務類

public class JobTest implements Job {
    
    @Autowired
    UserService userService;
    
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("任務執行中");
        System.out.println("userService:"+userService);
    }
}

能夠在spring容器啓動成功後執行這個任務,在任務類中嘗試注入UserService ,可是最後的結果是沒法注入。框架

3.三、解決注入問題

在構造方法中從spring容器中去獲取須要的beanide

public JobTest() {
        this.userService= SpringContextKit.getBean("userService");
    }

SpringContextKit代碼ui

/**
 * 獲取spring容器中的組件
 */
@Component
public class SpringContextKit implements ApplicationContextAware {
    private static ApplicationContext context = null;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     *
     * @param beanName 須要在接口實現類上標註 如@Service("userService")
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName){
        return (T) context.getBean(beanName);
    }
}

3.四、在spring.xml中配置任務

3.4.一、定義任務類

@Component
public class TaskBean {
    @Autowired
    UserService userService;
    private void executeTask(){
        System.out.println("任務執行中");
        System.out.println("userService:"+userService);
    }
}

經過@Component 註解將任務bean交由spring容器進行管理,那麼在此bean中就能夠使用容器中的其餘bena,好比這裏的userService。this

3.4.二、配置spring-quartz.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--jobDetail -->
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="taskBean"/>
        <property name="targetMethod" value="executeTask"/>
        <property name="concurrent" value="false"/>
    </bean>

    <!--jobDetail 觸發器 定義任務執行規則-->
    <bean id="trigger1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"/>
        <!--每五秒執行一次任務-->
        <property name="cronExpression" value="0/5 * * * * ?"/>
    </bean>


    <!--任務調度-->
    <bean id="schedule" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="trigger1"/>
            </list>
        </property>
        <property name="autoStartup" value="true"/>
    </bean>
</beans>
相關文章
相關標籤/搜索