Spring Boot集成Quartz

建立SpringBoot項目

參考:http://www.javashuo.com/article/p-nqmlkfay-bq.htmljava

添加Quartz依賴,配置pom文件

<!--用到Me-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>

建立任務調度配置文件ScheduledConfiguration.java

@Configuration
public class ScheduledConfiguration {

    /**
     * 定義JobDetail
     * @param schedledTasks
     * @return
     */
    @Bean
    public MethodInvokingJobDetailFactoryBean datailFactoryBean(SchedledTasks schedledTasks){
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        //設置對應的job對象
        bean.setTargetObject(schedledTasks);
        //設置schedledTasks對應的方法名
        bean.setTargetMethod("excute");
        return bean;
    }

    /**
     * 定義trigger
     * @param jobDetail
     * @return
     */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(MethodInvokingJobDetailFactoryBean jobDetail){
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
        trigger.setJobDetail(jobDetail.getObject());
        trigger.setCronExpression("0/5 * * ? * *");//每5秒執行一次
        return trigger;
    }

    /**
     * 定義scheduler
     * @param trigger
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean trigger){
        SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
        scheduler.setTriggers(trigger.getObject());
        return scheduler;
    }
}

建立SchedledTasks.java

@Component
public class SchedledTasks {

    public void excute(){
        //執行任務
        System.out.println("excute == " + new Date());
    }
}

測試

相關文章
相關標籤/搜索