Struts 2 + Quartz 2 scheduler integration example

Updated 2012-07-24
Article is updated to use latest Struts 2 and Quartz 2, and tested on Tomcat 6 and 7.

Struts 2 didn’t comes with any ready “Struts2-Quartz.jar” like plugin, the hack is use a standard Servlet Listener to link both frameworks together. See the relationship


Struts 2 <-- (Listener)--> Quartz <---> Scheduler task

In this tutorial, we show you how to integrate both Struts 2 and Quartz scheduler framework together.

Tools used :

  1. Struts 2.3.4
  2. Quartz 2.1.5
  3. Tomcat 6 or 7
  4. Maven 3
  5. Eclipse 4.2

1. Dependency Libraries

Not many dependencies, you just need the Struts 2 and Quartz jar file.

File : pom.xml


  ...
   <dependencies>

	<!-- Struts 2 -->
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.4</version>
	</dependency>

	<!-- Quartz framework -->
	<dependency>
		<groupId>org.quartz-scheduler</groupId>
		<artifactId>quartz</artifactId>
		<version>2.1.5</version>
	</dependency>

        <!-- for javax.servlet.* classes -->
	<dependency>
		<groupId>org.apache.tomcat</groupId>
		<artifactId>servlet-api</artifactId>
		<version>6.0.35</version>
	</dependency>

  </dependencies> 
  ...

2. Scheduler Job

Create a Quartz’s job and print out a single line.

File : SchedulerJob.java


package com.mkyong.quartz;

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

public class SchedulerJob implements Job {
	public void execute(JobExecutionContext context)
		throws JobExecutionException {

		System.out.println("Struts 2.3.4 + Quartz 2.1.5");

	}
}

3. Servlet Listener

Create standard servlet listener class, to do the integration works. It call the Quartz scheduler framework inside the contextInitialized() method. During the Servlet container initialization, this contextInitialized() method will be executed automatically.

File : QuartzSchedulerListener.java


package com.mkyong.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import com.mkyong.quartz.SchedulerJob;

public class QuartzSchedulerListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent arg0) {
		//
	}

	public void contextInitialized(ServletContextEvent arg0) {

		JobDetail job = JobBuilder.newJob(SchedulerJob.class)
			.withIdentity("anyJobName", "group1").build();

		try {

			Trigger trigger = TriggerBuilder
			  .newTrigger()
			  .withIdentity("anyTriggerName", "group1")
			  .withSchedule(
			     CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
			  .build();

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.start();
			scheduler.scheduleJob(job, trigger);

		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}
}

4. web.xml

Put the listener class QuartzSchedulerListener.java into the web.xml file.

File : web.xml


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Struts 2 Web Application</display-name>

	<filter>
	  <filter-name>struts2</filter-name>
	  <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
          </filter-class>
	</filter>

	<filter-mapping>
	  <filter-name>struts2</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>

	<listener>
	  <listener-class>
            com.mkyong.listener.QuartzSchedulerListener
          </listener-class>
	</listener>

</web-app>

5. Demo

After the Struts 2 project is started, the registered listener class QuartzSchedulerListener.java will be fired, and call the Quartz scheduled job to execute the SchedulerTask.printSchedulerMessage() method at every 10 seconds.


INFO: Overriding property struts.i18n.reload - old value: false new value: true
Jul 23, 2012 4:56:47 PM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true
Jul 23, 2012 4:56:48 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 23, 2012 4:56:48 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 23, 2012 4:56:48 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/38  config=null
Jul 23, 2012 4:56:48 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1215 ms
Struts 2.3.4 + Quartz 2.1.5
Struts 2.3.4 + Quartz 2.1.5

Download Source Code

Download it –Struts2-Quartz-Example.zip (22 KB)

References

  1. Quartz scheduler example
  2. Struts + Quartz integration example
  3. Struts 2 + Spring + Quartz integration example
  4. Struts + Spring + Quartz integration example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
14 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
13 Comment authors
Filippo PizzicolaNIC NICPGK.Reddyrajesh kumarAhmed Khalil Elharim Recent comment authors
newest oldest most voted
Filippo Pizzicola
Guest
Filippo Pizzicola

Hi, thanks a lot for this tutorial, but when I run my application with Quartz, all my schedules are running twice. Does anyone have any idea?

NIC NIC
Guest
NIC NIC

how we can get access of database in job class with this approach.

PGK.Reddy
Guest
PGK.Reddy

Hi I download the code and when i try to run it i am getting error as In Consloe:Oct 01, 2014 12:09:32 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:Program FilesJavajre7bin;C:WindowsSunJavabin;C:Windowssystem32;C:Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:Program FilesCommon FilesMicrosoft SharedWindows Live;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:Program FilesWindows LiveShared;C:Program FilesTortoiseSVNbin;D:Eclipse Juno;;. Oct 01, 2014 12:09:32 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.j2ee.server:Struts2Example’ did not find a matching property. Oct 01, 2014 12:09:33 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler [“http-bio-2223”] Oct 01, 2014 12:09:33 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler… Read more »

rajesh kumar
Guest
rajesh kumar

I compile the same project its running fine. But Iam not able to stop my server. Please suggest me what wrong i did. Iam using bean class also in my code.

Ahmed Khalil Elharim
Guest
Ahmed Khalil Elharim

thank you very very very much doctor!!

Mark Peter
Guest
Mark Peter

I tried the same example but instead using the maven i gone with the jars. am getting error at compilation in the line JobDetail job = JobBuilder.newJob(SchedulerJob.class).withIdentity(“anyJobName”, “group1”).build(); from Servlet Listner.

The error states
no suitable method found for newJob(Class)
method JobBuilder.newJob(Class) is not applicable
(actual argument Class cannot be converted to Class by method invocation conversion)
method JobBuilder.newJob() is not applicable
(actual and formal argument lists differ in length)

Kindly suggest me how to solve this.

Pramod
Guest
Pramod

will you please provide list of jar files required to execute above code……. I am unable to execute the code….
Thanx in advance!!!!!!

priyank gupta
Guest
priyank gupta

nice tutorial helped me

Rohith
Guest
Rohith

Hi I implemented in my project. But I am getting the following error
QuartzSchedulerListener failed: java.lang.IncompatibleClassChangeError: Implementing class.
Please help.Thanks in advance

vish
Guest
vish

Hi,
I deployed the code but it is giving me some issues

22:52:57,666 ERROR [STDERR] SLF4J: Your binding is version 1.5.5 or earlier.
22:52:57,670 ERROR [STDERR] SLF4J: Upgrade your binding to version 1.6.x. or 2.0
.x

trackback
Quartz Scheduler Tutorial ‹ ???

[…] Struts 2 + Quartz 2 scheduler example Integrate Quartz 2 with Struts 2 directly. […]

David Cortez
Guest
David Cortez

very good tutorial!! Thanks a Lot!!!!2X

ramesh
Guest
ramesh

very good tutorial!! Thanks a Lot!!!!

aneer
Guest
aneer

Greate tut… Boss.. really worked….