Spring boot quartz

2018-10-24  本文已影响0人  放不下FBX

① 那么我们首先看需要的包,先看看pom.xml文件:

    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency><!-- 该依赖必加,里面有sping对schedule的支持 -->
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
    </dependency>

我只截取了部分,除了这些以外,如果你是spring boot 的项目一定还要有相关配置文件,别指望我会贴出来,做梦!摔!

② 先写一个监听器保证项目启动的时候会调用到,我们的定时任务,代码如下:

package task;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**

③ 写我们自己的定时器,用来触发我们的任务:

package task;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
/**

}

④ 接下来就写我们具体的任务如下:
第一个定时任务

package task;

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

import java.util.Date;

/**

第二个定时任务

package task;

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

import java.util.Date;

/**

启动测试Demo(启动方法main直接写在了Controller里面,配个spring boot 注解@SpringBootApplication):

package task;

import org.quartz.SchedulerException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**

上一篇 下一篇

猜你喜欢

热点阅读