首页 > 代码库 > quartz搭建与应用

quartz搭建与应用

1.添加依赖

依赖包括Quartz和logback

<dependencies>    <dependency>       <groupId>org.quartz-scheduler</groupId>       <artifactId>quartz</artifactId>       <version>2.2.0</version>    </dependency>    <dependency>       <groupId>ch.qos.logback</groupId>       <artifactId>logback-classic</artifactId>       <version>1.1.0</version>    </dependency></dependencies>

 

2.简单搭建

引入jar包

技术分享

 

在quartz.properties中配置quartz

org.quartz.scheduler.instanceName = MyScheduler
#个数随实际情况而定org.quartz.threadPool.threadCount = 3org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

logback.xml,日志框架logback的配置

<configuration>    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">        <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder             by default -->        <encoder>            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n            </pattern>        </encoder>    </appender>    <appender name="FILE" class="ch.qos.logback.core.FileAppender">        <file>D:/logs/quartz_task_application.log</file>        <encoder>            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n            </pattern>        </encoder>    </appender>    <root level="debug">        <appender-ref ref="STDOUT" />        <appender-ref ref="FILE" />    </root></configuration>

 

HelloJob.java,具体要执行任务

package No01;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class HelloJob implements Job {        Logger logger = LoggerFactory.getLogger(this.getClass());    @Override    public void execute(JobExecutionContext arg0) throws JobExecutionException {        // 此任务仅打印日志便于调试、观察        this.logger.debug(this.getClass().getName() + " trigger...");    }}

定义执行任务的时间和任务内容

package No01;import java.util.concurrent.TimeUnit;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SimpleScheduleBuilder;import org.quartz.Trigger;import org.quartz.TriggerBuilder;import org.quartz.impl.StdSchedulerFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class Bootstrap {    private static Logger logger = LoggerFactory.getLogger(Bootstrap.class);    public static void main(String[] args) {      try {         // 获取Scheduler实例        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();        scheduler.start();        // 具体任务        JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();       // 触发时间点       SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever();       Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startNow().withSchedule(simpleScheduleBuilder).build();    // 交由Scheduler安排触发       scheduler.scheduleJob(job, trigger);             /* 为观察程序运行,此设置主程序睡眠3分钟才继续往下运行(因下一个步骤是“关闭Scheduler”) */      try {           TimeUnit.MINUTES.sleep(3);          } catch (InterruptedException e) {                e.printStackTrace();        }    // 关闭Scheduler       scheduler.shutdown();      } catch (SchedulerException se) {          logger.error(se.getMessage(), se);      }    }}

3.在web应用中使用quartz

 

Quartz常在Web中应用,常见的是交由Spring托管的形式。这里介绍Quartz在Web应用中单独使用。

一般Web应用启动时,应注册已经确定的定时任务;一些动态的、未确定触发时间的定时任务,后续可通过静态的Scheduler注册。

使用监听器在应用启动时注册,并在web.xml注册这个监听器;在关闭Web应用时,要注销定时任务。

其他配置文件、Java类与上例子相同,只是把这里注册定时任务的地方换成此监听器。

package No02;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SimpleScheduleBuilder;import org.quartz.Trigger;import org.quartz.TriggerBuilder;import org.quartz.impl.StdSchedulerFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import No01.HelloJob;/** * Application Lifecycle Listener implementation class AListener * */public class ApplicationContextListener implements ServletContextListener {        private Logger logger = LoggerFactory.getLogger(this.getClass());        public static Scheduler scheduler = null;    @Override    public void contextInitialized(ServletContextEvent arg0) {        this.logger.info("The application start...");                /* 注册定时任务 */        try {            // 获取Scheduler实例            scheduler = StdSchedulerFactory.getDefaultScheduler();            scheduler.start();            // 具体任务            JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();            // 触发时间点            SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever();            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startNow().withSchedule(simpleScheduleBuilder).build();            // 交由Scheduler安排触发            scheduler.scheduleJob(job, trigger);                        this.logger.info("The scheduler register...");        } catch (SchedulerException se) {            logger.error(se.getMessage(), se);        }    }        @Override    public void contextDestroyed(ServletContextEvent arg0) {        this.logger.info("The application stop...");                /* 注销定时任务 */        try {            // 关闭Scheduler            scheduler.shutdown();                        this.logger.info("The scheduler shutdown...");        } catch (SchedulerException se) {            logger.error(se.getMessage(), se);        }    }}

<listener>   <listener-class>No02.ApplicationContextListener</listener-class>
</listener>

 在eclipse调试中,可能发现无法看到contextDestroy方法的执行,请注意使用stop的方式关闭应用,而不是terminate

 图一

技术分享

 

图二

技术分享

4常用的Cron Schedule

 相对于其他方式定义定时任务的触发时间,我们较常用Cron Schedule。

// 具体任务JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();// 触发时间点CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 * * * * ? *");Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")        .withSchedule(cronScheduleBuilder).build();// 交由Scheduler安排触发scheduler.scheduleJob(job, trigger);

 本文参考:http://www.cnblogs.com/nick-huang/p/4848843.html

 

quartz搭建与应用