Java – Job Scheduling in web application with quartz API

 

Scheduling job in web application is important part of application. Today most of the companies and programmer keep eye on the performance of the application. They do it by running most of work in background of the application without the knowledge of the user. Manual work is going to automize in these days and run in idle time of working hours.

If you want to send email at fixed time, send newsletter, taking backup of database, synchronizing of databases, setting up reminder, all need to run schedule job at particular interval.

Java is bundled with timer class to perform scheduling task and make your own logics to perform scheduling by while loop with sleep thread. But this is not good way to schedule more than one job at a time.

Timer class is good option for scheduling task, but it still doesn’t have optional day selection like in cron of linux.

Quartz is scheduling API which fulfill your all need and easy to use and initialization of scheduling.

We can use simple trigger with millisecond and repeat jobs and set repeat intervals. Advance Trigger CronTrigger works exactly same unix cron. In CronTrigger we can define, selected days e.g. Wednesday, Friday weekly, monthly and yearly.

In quartz, we can monitor our jobs and in between can stop jobs.

Quartz scheduling can be used with servlet initialization and struts initialization.

In servlet initialization, we have to define in web.xml and in struts we have to define plugin in struts-config.xml.

1. Quartz with Simple Servlet

web.xml

<web-app>
 <display-name>timer</display-name>
	
	<servlet>
	 <servlet-name>InitializeServlet</servlet-name>
	 <servlet-class>com.cron.InitializeServlet</servlet-class> 
	 <load-on-startup>1</load-on-startup>
	</servlet>
	
</web-app>

InitializeServlet.java

package com.cron;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;


public class InitializeServlet extends HttpServlet {


 public void init() throws ServletException {
    
    try {
        System.out.println("Initializing NewsLetter PlugIn");
        
        CronScheluder objPlugin = new CronScheluder();
        
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    
  }
 
}

CronScheluder.java

package com.cron;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class CronScheluder {

    public CronScheluder() throws Exception {
        
        SchedulerFactory sf = new StdSchedulerFactory();
        
        Scheduler sche = sf.getScheduler();
        
        sche.start();
        
        JobDetail jDetail = new JobDetail("Newsletter", "NJob", MyJob.class);
        
        //"0 0 12 * * ?" Fire at 12pm (noon) every day
        //"0/2 * * * * ?" Fire at every 2 seconds every day
        
 CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?");
        
        sche.scheduleJob(jDetail, crTrigger);
    }
}

MyJob.java

package com.cron;

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


public class MyJob implements Job {

    public void execute(JobExecutionContext context)
     throws JobExecutionException {
    
      System.out.println("Cron executing ");
        
    }
}

Another option to use quartz api

2. Quartz with ServletContextListener

web.xml

<web-app>
	
	<display-name>timer</display-name>
	
	  <listener>
	     <listener-class>com.cron.StartCron</listener-class>
	  </listener>
	  
</web-app>

StartCron.java

package com.cron;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class StartCron implements ServletContextListener{
    
    public void contextDestroyed(ServletContextEvent arg0)
    {
        System.out.println("Stopping Application successfully");
    }
    
    public void contextInitialized(ServletContextEvent arg0) 
    {
       System.out.println("Initializing Application successfully");
       
       try{
         CronScheluder objPlugin = new CronScheluder();
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
     }          
}

All rest of code is same and use

CronScheluder.java

MyJob.java

3. Quartz with Struts

You have to define in struts-config.xml file a plugin

 <plug-in className="com.cron.StrutsImp">
         <set-property property="startOnLoad" value="true"/>
         <set-property property="startupDelay" value="0"/>
 </plug-in>

StrutsImp.java

package com.cron;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

public class StrutsImp implements PlugIn {

 public static final String PLUGIN_NAME_KEY = StrutsImp.class.getName();

 public void init(ActionServlet servlet, ModuleConfig config)
  throws ServletException {
    
    try {
        System.out.println("Initializing PlugIn");
        
        ServletContext context = null;
        
        context = servlet.getServletContext();

        CronScheluder objPlugin = new CronScheluder(context);
        
        context.setAttribute(PLUGIN_NAME_KEY, objPlugin);
        
        System.out.println("scheluder started successfully...");
        
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    
  }
 
 public void destroy()
 {
     
 }
 
}

Download API to Run this example Quartz 1.6.6

 

12 Responses to “Java – Job Scheduling in web application with quartz API”

  1. mlavannis says:

    In CronScheluder.java:
    SchedulerFactory sf = new StdSchedulerFactory();

    does not seem to work. I have put a print statement before and after it – the first one gets printed, the next does not. Looking at the StdSchedulerFactory constructor, I see that it is an empty function.

    I am clueless! Can you please help?? Thanks!

  2. mlavannis says:

    My bad! I had forgotten to upload the quartz jar. It is working now :) And thanks a lot for this page…

  3. wiam says:

    thank you for the example: D
    hand can you help me with this error:

    org.quartz.SchedulerConfigException: Thread count must be> 0
    org.quartz.simpl.SimpleThreadPool.initialize (SimpleThreadPool.java: 241)
    org.quartz.impl.StdSchedulerFactory.instantiate (StdSchedulerFactory.java: 1190)
    org.quartz.impl.StdSchedulerFactory.getScheduler (StdSchedulerFactory.java: 1399)
    test.CronScheluder. (CronScheluder.java: 17)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance (Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance (Unknown Source)
    java.lang.reflect.Constructor.newInstance (Unknown Source)
    java.lang.Class.newInstance0 (Unknown Source)
    java.lang.Class.newInstance (Unknown Source)
    org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java: 104)
    org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java: 216)
    org.apache.coyote.http11.Http11Processor.process (Http11Processor.java: 844)
    $ Http11ConnectionHandler.process org.apache.coyote.http11.Http11Protocol (Http11Protocol.java: 634)
    org.apache.tomcat.util.net.JIoEndpoint $ Worker.run (JIoEndpoint.java: 445)
    java.lang.Thread.run (Unknown Source)

    merci pour l’exemple :D
    main pouvez vous m’aider avec cette erreur:

    org.quartz.SchedulerConfigException: Thread count must be > 0
    org.quartz.simpl.SimpleThreadPool.initialize(SimpleThreadPool.java:241)
    org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1190)
    org.quartz.impl.StdSchedulerFactory.getScheduler(StdSchedulerFactory.java:1399)
    test.CronScheluder.(CronScheluder.java:17)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    java.lang.Class.newInstance0(Unknown Source)
    java.lang.Class.newInstance(Unknown Source)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
    java.lang.Thread.run(Unknown Source)

  4. Vikas Gupta says:

    java.lang.NoClassDefFoundError: org/quartz/SchedulerFactory
    at com.kcsv.model.InitializeServlet1.init(InitializeServlet1.java:27)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4149)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4458)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Caused by: java.lang.ClassNotFoundException: org.quartz.SchedulerFactory
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    … 18 more
    Apr 5, 2010 8:59:00 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /QuartTest threw load() exception
    javax.servlet.ServletException: Servlet.init() for servlet InitializeServlet1 threw exception
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1214)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4149)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4458)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Apr 5, 2010 8:59:00 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    Apr 5, 2010 8:59:01 PM org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009

  5. Sathya says:

    I dont see the responce for createing Schedular.controll is not movinf forward after creating a schedular.

    I am using quartz1.6 jar.
    please suggest!!

  6. Yves says:

    With your example, how to you take care the scheduler is shut down properly when tomcat is stopped?

  7. Nikita says:

    Gr8 job. simple code to get the clear view.
    Thanks a lot

  8. Vishwanth says:

    Hi I’m getting the following error.

    java.lang.ClassNotFoundException: CronJobTest.com.cron.InitializeServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1068)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3996)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4266)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    Please help.

  9. AL says:

    SAME HERE:

    java.lang.ClassNotFoundException: CronJobTest.com.cron.InitializeServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1068)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3996)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4266)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)

  10. Alban Pro says:

    Vishwanth and AL DO NOT include the :

    <servlet>
    <servlet-name>InitializeServlet</servlet-name>
    <servlet-class>com.cron.InitializeServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>

    in Web.xml that is in Tomcat Server directory but in the Web.xml that is in WEB-INF….

  11. someone says:

    I do not get those people like this.

    I would really vote for this as worst ever. Alot of people who has problems with your code and no answers at all.

  12. Java helper says:

    Please use old jar api

    Quartz 1.x.x version API to run this.

    Download this API jar

    http://quartz-scheduler.org/files/releases/quartz-1.6.6.zip

    and replace with newer one than run.

Leave a Reply