Simple example for Quartz 2.2 and Tomcat 7

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

I want to create a scheduler with Quartz 2.2 in java dynamic web application. I am new to this task. I tried all the tutorials around the web. I trying context listener method to initialize the scheduler. It doesn't seem like working. The hello world program only works in general java application. for web application its looks tricky.

pom.xml:

    4.0.0test.ananthtest-appwar1.0-SNAPSHOTtest-app Maven Webapphttp://maven.apache.orgorg.quartz-schedulerquartz2.2.1org.apache.tomcatservlet-api6.0.30log4jlog4j1.2.16org.quartz-schedulerquartz-jobs2.2.0org.slf4jslf4j-api1.6.6junitjunit3.8.1testtest-app

quartz.properties:

#org.quartz.scheduler.instanceName = MyScheduler org.quartz.threadPool.threadCount = 3 org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore  # Main Quartz configuration org.quartz.scheduler.skipUpdateCheck = true org.quartz.scheduler.instanceName = MyQuartzScheduler org.quartz.scheduler.jobFactory.class = org.quartz.simpl.SimpleJobFactory org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool #org.quartz.threadPool.threadCount = 5 

HelloJob.java:

    package com.test;      import org.quartz.Job;     import org.quartz.JobExecutionContext;     import org.quartz.JobExecutionException;      public class HelloJob implements Job {  public HelloJob() { }  public void execute(JobExecutionContext context)         throws JobExecutionException {      System.out.println("Hello!  HelloJob is executing."); }     } 

servlet.java package com.test;

import static org.quartz.JobBuilder.newJob; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import static org.quartz.TriggerBuilder.newTrigger;  import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet;  import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory;  public class MyServlet extends HttpServlet {      /**      *       */     private static final long serialVersionUID = 1567185871113714035L;      public void init(ServletConfig cfg) {         String key = "org.quartz.impl.StdSchedulerFactory.KEY";         ServletContext servletContext = cfg.getServletContext();         StdSchedulerFactory factory = (StdSchedulerFactory) servletContext                 .getAttribute(key);         // Scheduler quartzScheduler = factory.getScheduler("MyQuartzScheduler");         Scheduler sched;         try {             sched = factory.getScheduler("MyQuartzScheduler");             //sched = factory.getScheduler();//MyQuartzScheduler             sched.start();              // define the job and tie it to our HelloJob class             JobDetail job = newJob(HelloJob.class).withIdentity("myJob",                     "group1").build();              // Trigger the job to run now, and then every 40 seconds             Trigger trigger = newTrigger()                     .withIdentity("myTrigger", "group1")                     .startNow()                     .withSchedule(                             simpleSchedule().withIntervalInSeconds(4)                                     .repeatForever()).build();              // Tell quartz to schedule the job using our trigger             sched.scheduleJob(job, trigger);         } catch (SchedulerException e) {             e.printStackTrace();         }      } } 

Web.xml:

  quartz:shutdown-on-unloadfalsequartz:wait-on-shutdowntruequartz:start-scheduler-on-loadtruequartz:config-file/WEB-INF/quartz.properties                 org.quartz.ee.servlet.QuartzInitializerListener             com.test.ApplicationStartupArchetype Created Web Application

I am using maven web app archtype.

回答1:

Contents

  • Eclipse project
  • With Maven
  • XML-Less

Eclipse project

If you are using a typical project in eclipse, the most basic example has a structure similar to:

C:. | +---src |   |   log4j.dtd |   |   log4j.xml |   |   quartz.properties |   |   quartz_data.xml |   | |   \---org |       \---paulvargas |           \---test |               \---quartz |                       TestJob.java | \---WebContent     \---WEB-INF         |   web.xml         |         \---lib                 jta-1.1.jar                 log4j-1.2.17.jar                 quartz-2.1.5.jar                 slf4j-api-1.6.5.jar                 slf4j-log4j12-1.6.5.jar 

Where the code of each of the files is as follows:

web.xml

org.quartz.ee.servlet.QuartzInitializerListener

quartz.properties

# ----------------------------- Threads --------------------------- # # How many jobs can run at the same time? org.quartz.threadPool.threadCount=5  # ----------------------------- Plugins --------------------------- # # Class to load the configuration data for each job and trigger. # In this example, the data is in an XML file. org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin 

quartz_data.xml

TestJoborg.paulvargas.test.quartz.TestJobTestJobTestJob0 0/5 * 1/1 * ? *

The job is executed every 5 minute(s) (see the expression 0 0/5 * 1/1 * ? * in the cron-expression tag). If you want another expression, you can build it with http://www.cronmaker.com/

TestJob.java

package org.paulvargas.test.quartz;  import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException;  public class TestJob implements Job {      @Override     public void execute(final JobExecutionContext ctx)             throws JobExecutionException {          System.out.println("Executing Job");      }  } 

log4j.xml


With Maven

If you are using Maven, the structure for the same project is:

C:. |   pom.xml | \---src     \---main         +---java         |   \---org         |       \---paulvargas         |           \---test         |               \---quartz         |                       TestJob.java         |         +---resources         |       log4j.dtd         |       log4j.xml         |       quartz.properties         |       quartz_data.xml         |         \---webapp             |   index.jsp             |             \---WEB-INF                     web.xml 

And the file pom.xml:

4.0.0testBasicQuartzwar1.0-SNAPSHOTBasicQuartzhttp://maven.apache.orgjavax.servletservlet-api2.5providedorg.quartz-schedulerquartz2.2.1org.quartz-schedulerquartz-jobs2.2.1javax.transactionjta1.1org.slf4jslf4j-log4j121.7.5org.apache.maven.pluginsmaven-compiler-plugin2.0.21.51.5

XML-less

* This requires Servet 3.0+ (Tomcat 7+, Glassfish 3+, JBoss AS 7)

You only need two files: TestJob.java from the previous example and the following listener:

import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.annotation.WebListener;  import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.ee.servlet.QuartzInitializerListener; import org.quartz.impl.StdSchedulerFactory;  @WebListener public class QuartzListener extends QuartzInitializerListener {      @Override     public void contextInitialized(ServletContextEvent sce) {         super.contextInitialized(sce);         ServletContext ctx = sce.getServletContext();         StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY);         try {             Scheduler scheduler = factory.getScheduler();             JobDetail jobDetail = JobBuilder.newJob(TestJob.class).build();             Trigger trigger = TriggerBuilder.newTrigger().withIdentity("simple").withSchedule(                     CronScheduleBuilder.cronSchedule("0 0/1 * 1/1 * ? *")).startNow().build();             scheduler.scheduleJob(jobDetail, trigger);             scheduler.start();         } catch (Exception e) {             ctx.log("There was an error scheduling the job.", e);         }     }  } 

To avoid conflicts, do not set the default listener in the web.xml at the same time. With this last example, the default number of threads is 10. Since the scheduler started in stand-by mode, it is necessary to call scheduler.start();. The "simple" identity is optional, but you can use it for reschedule the job (That's great!). e.g.:

ServletContext ctx = request.getServletContext(); StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QuartzListener.QUARTZ_FACTORY_KEY); Scheduler scheduler = factory.getScheduler(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("simple").withSchedule(         CronScheduleBuilder.cronSchedule(newCronExpression)).startNow().build(); Date date = scheduler.rescheduleJob(new TriggerKey("simple"), trigger); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!