Quartz 1.6 scheduler tutorial

Quartz is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time.

This tutorial show you how to develop a scheduler job using Quartz 1.6.3.

Note
This example is a bit outdate, unless you are still using the old Quartz 1.6.3 library, otherwise, you may interest of this latest Quartz 2.1.5 example.

1. Download Quartz

You can get the Quartz library from official website or Maven central repository

File : pom.xml


	<dependencies>

		<!-- Quartz API -->
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>quartz</artifactId>
			<version>1.6.3</version>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.directory.studio</groupId>
			<artifactId>org.apache.commons.logging</artifactId>
			<version>1.1.1</version>
		</dependency>

	</dependencies>

2. Quartz Job

Quartz job is defined what you want to run?

File : HelloJob


package com.mkyong.common;

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

public class HelloJob implements Job
{
	public void execute(JobExecutionContext context)
	throws JobExecutionException {
		
		System.out.println("Hello Quartz!");	
		
	}
	
}

3. Quartz Trigger

Quartz trigger is defined when the Quartz will run your above Quartz’s job?

There are two types of Quartz triggers :

  • SimpleTrigger – Allows to set start time, end time, repeat interval.
  • CronTrigger – Allows Unix cron expression to specify the dates and times to run your job.
Unix cron expression
The Unix cron expression is highly flexible and powerful, you can learn and see many cron expression examples in following websites.

  1. http://en.wikipedia.org/wiki/CRON_expression
  2. http://www.quartz-scheduler.org/docs/examples/Example3.html

SimpleTrigger – Run every 30 seconds.


        SimpleTrigger trigger = new SimpleTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
    	trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    	trigger.setRepeatInterval(30000);

CronTrigger – Run every 30 seconds.


    	CronTrigger trigger = new CronTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setCronExpression("0/30 * * * * ?");

4. Scheduler

Scheduler class links both “Job” and “Trigger” together and execute it.


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

5. Full Example

Here are two full examples to use Quartz, via SimpleTrigger and CronTrigger.

SimpleTrigger example
Run very 30 seconds with a 1 second delay for the first time of execution.


package com.mkyong.common;

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerExample 
{
    public static void main( String[] args ) throws Exception
    {
       	JobDetail job = new JobDetail();
    	job.setName("dummyJobName");
    	job.setJobClass(HelloJob.class);
    	
    	//configure the scheduler time
    	SimpleTrigger trigger = new SimpleTrigger();
    	trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
    	trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    	trigger.setRepeatInterval(30000);
    	
    	//schedule it
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);

    }
}

CronTrigger example
Same, run the job at every 30 seconds.


package com.mkyong.common;

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

public class CronTriggerExample 
{
    public static void main( String[] args ) throws Exception
    {
    	
    	JobDetail job = new JobDetail();
    	job.setName("dummyJobName");
    	job.setJobClass(HelloJob.class);
    	    	
    	CronTrigger trigger = new CronTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setCronExpression("0/30 * * * * ?");
    	
    	//schedule it
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);
    
    }
}

Download Source Code

Download it – QuartzExample.zip (14kb)

References

  1. Quartz Official Website

58 comments on “Quartz 1.6 scheduler tutorial

  1. Hi, as JobDetail is now an interface so can’t create object of this now.

    Reply
  2. Hi,
    I want to schedule my java main program. i did all the steps and it works fine but my test environment does not have eclipse and I can only deploy my code and make it run either windows scheduler or through a jar file. How should I schedule it Could you please guide me on this?

    Reply
  3. What are the advantages of using spring wrapper classes like JobDetailFactoryBean, CronTriggerFactoryBean over simple quartz JobDetail and Triggers etc.

    Reply
  4. In your full example SimpleTrigger have no name it give the exception *Trigger’s name cannot be null*

    Reply
    1. You can add Trigger name as:

      trigger.setName(“SampleTrigger”);

      Reply
  5. In “5. Full Example”, “trigger.setName(“dummyTriggerName”);” is missing.

    Reply
  6. Hi Mkyong,
    It seems that for latest Quartz version (2.2.1), you can not instantiate “JobDetail”. I think need to update all these tutorials. I’d like to help you on this.

    Reply
  7. I am getting an error like org.quartz is not resolved.I imported quartz jar 1.8.5.How to solve my issue ,Can you please resolve it.

    Reply
  8. Hi,

    I am able to schedule the job as given above in a standalone program, I am trying to shut down the job when ever I required so written another java program but the scheduler unable to get the handle to delete the job or interrupt the job or unschedule.
    Implemented InterruptableJob for the job.

    Tried through initializing the Properties file.
    The Below code works as expected, but unable to stop the job through standalone.

    JobDetail job = JobBuilder.newJob(BatchSchedulerJOB.class)
    .withIdentity(“MJob”, “MGroup”).build();
    TriggerKey key = new TriggerKey(“MGroup.MTrigger”);
    Trigger trigger = TriggerBuilder
    .newTrigger().withIdentity(key)
    //.withIdentity(“MTrigger”, “MGroup”)
    .forJob(job)
    .withSchedule(
    CronScheduleBuilder.cronSchedule(“59 * * * * ?”))

    .build();
    StdSchedulerFactory std = new StdSchedulerFactory();
    Properties prop = new Properties();
    prop.load(new FileInputStream(“./myquartz.properties”));

    std.initialize(prop);
    Scheduler scheduler = std.getScheduler();
    scheduler.scheduleJob(job, trigger);
    scheduler.start();

    My quartz.properties file is as below even by default scheduler instance it works.

    org.quartz.scheduler.instanceName: MyScheduler
    org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
    org.quartz.threadPool.threadCount: 10
    org.quartz.threadPool.threadPriority: 5

    Any thoughts in this regard would be appreciable.

    Thanks, Sri

    Reply
  9. I use quartz(ver 2.1.0) for my bundle in OSGIFW, but when use
    SchedulerFactory sf = new StdSchedulerFactory()
    sched = sf.getScheduler()
    i got an error:
    -> org.quartz.SchedulerConfigException: Unable to instantiate class load helper class: org.quartz.simpl.CascadingClassLoadHelper cannot be cast to org.quartz.spi.ClassLoadHelper [See nested exception: java.lang.ClassCastException: org.quartz.simpl.CascadingClassLoadHelper cannot be cast to org.quartz.spi.ClassLoadHelper]

    i try to find another quartz library in my location, but has only one (that jar file)

    Any idea how correct this ?

    Thanks

    Reply
  10. How to handle a job when we do
    sched.interrupt(jobName , jobGroup);

    I need to get the status of a job when it got interrupted. is there any Job Handlers are available??

    Reply
  11. Hi,
    I am getting error in almost every line
    method setname(String) is undefined for type JobDetail
    method setJobClass(Class) is undefined for type JobDetail

    and same with the methods of SimpleTrigger.

    please help.
    i m using Quarts 2.1.7

    Reply
  12. Quartz 2 APIs are big different with Quartz 1(1.5,1.6 and 1.7) Class JobDetail{
    }

    quartz-1.6.6:
    http://javasourcecode.org/html/open-source/quartz/quartz-1.6.6/org/quartz/JobDetail.html

    Quartz 2:
    public interface JobDetail extends Serializable, Cloneable {
    }

    // we have to create JobDetail in the below way.
    JobDetail job = newJob(HelloJob.class)

    // we have to create Trigger in the below way.
    Trigger trigger = newTrigger()

    Don’t foget to improt the below one
    import static org.quartz.JobBuilder.*;
    import static org.quartz.TriggerBuilder.*;

    Reply
  13. iam new to the quartz scheduling ,how can we set quartz properties,should we create an XML file for that?

    Reply
  14. Apr 03, 2013 12:22:48 AM org.quartz.simpl.SimpleThreadPool initialize
    INFO: Job execution threads will use class loader of thread: main
    Apr 03, 2013 12:22:48 AM org.quartz.core.SchedulerSignalerImpl
    INFO: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
    Apr 03, 2013 12:22:48 AM org.quartz.core.QuartzScheduler
    INFO: Quartz Scheduler v.1.6.3 created.
    Apr 03, 2013 12:22:48 AM org.quartz.simpl.RAMJobStore initialize
    INFO: RAMJobStore initialized.
    Apr 03, 2013 12:22:48 AM org.quartz.impl.StdSchedulerFactory instantiate
    INFO: Quartz scheduler ‘DefaultQuartzScheduler’ initialized from default resource file in Quartz package: ‘quartz.properties’
    Apr 03, 2013 12:22:48 AM org.quartz.impl.StdSchedulerFactory instantiate
    INFO: Quartz scheduler version: 1.6.3
    Apr 03, 2013 12:22:48 AM org.quartz.core.QuartzScheduler start
    INFO: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
    Apr 03, 2013 12:23:00 AM org.quartz.core.ErrorLogger schedulerError
    SEVERE: An error occured instantiating job to be executed. job= ‘DEFAULT.dummyJobName’
    org.quartz.SchedulerException: Problem instantiating class ‘com.java.scheduler.HelloJob1’ [See nested exception: java.lang.IllegalAccessException: Class org.quartz.simpl.SimpleJobFactory can not access a member of class com.java.scheduler.HelloJob1 with modifiers “”]
    at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:57)
    at org.quartz.core.JobRunShell.initialize(JobRunShell.java:132)
    at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:387)
    Caused by: java.lang.IllegalAccessException: Class org.quartz.simpl.SimpleJobFactory can not access a member of class com.java.scheduler.HelloJob1 with modifiers “”
    at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:55)
    … 2 more

    Apr 03, 2013 12:23:00 AM org.quartz.simpl.RAMJobStore triggeredJobComplete
    INFO: All triggers of Job DEFAULT.dummyJobName set to ERROR state.

    I am getting this exception…please any body help to sort out this problem..
    Thanks in advance.

    Reply
  15. Can you Please,
    give me the Quartz misfire jobs Example.

    Reply
  16. how should i fix this error? “org.quartz.CronTrigger is abstract; cannot be instantiated”. Help!

    Reply
  17. java.lang.UnsupportedClassVersionError: Bad version number in .class file
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Exception in thread “main”

    Reply
  18. to schedule with a specific dans of the month , I try to use the quartz 2.1 instead of quartz 1.5 but it cause an error in scheduler.getJobDtail , how can I resolve the problem

    Reply
      1. “org.quartz.scheduler.instanceName = MyScheduler
        org.quartz.threadPool.threadCount = 3
        org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
        org.quartz.plugin.jobInitializer.class =org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
        org.quartz.plugin.jobInitializer.fileNames = quartz-config.xml
        org.quartz.plugin.jobInitializer.failOnFileNotFound = true”

        how can we create a quartz.properties file using eclipse
        wat is the mapping should be done in web.xml

        Reply
  19. Great amazing issues here. I am very satisfied to see your article. Thanks so much and i’m looking forward to touch you. Will you please drop me a e-mail?

    Reply
  20. After Downloading the code – the main directory is Spring example. Do we need Springs framework to run this code?

    Reply
    1. My mistake, forgot to rename the folder, you DON’T need Spring to run Quartz.

      Reply
  21. hi Mkyong,

    I am doing a study for selecting a suitable scheduler for my project. as part of this I got your page. can you help me to get the below information.

    1) What is the Request and Response Interface? Corba/RMI/java API ?
    2) any Scalability Issues ? like we may need to schedule 30K, 40K and 50K jobs now. tomorrow it may increase to more.
    3) any Performance Issues ?
    4) what is the DataBase it uses internally?
    5) any Pros/cons
    6) Remarks

    Thanks for your time.

    Reply
  22. From Best Practices on Quartz-Scheduler.org: “Only store primitive data types (including Strings) in JobDataMap to avoid data serialization issues short and long-term.”

    Reply
    1. q7NhOS+6lQLF6o8WVTn/Ke9GoduC4aSwfs5u0ZKsYBWIoaVhWRCzrWt89rYYrLrtpHMX2Be9jGuIhRydYjBnq6CFqC2/HadKsj47tVP4yuG+w32Sldu6YnuVhcZ6n02/FdGB1w==

      Reply
  23. I need to kick of job using Quartz when ever there is an update in our source DB tables. How can we implement using Controm M scheduler with Quartz?

    Reply
  24. This is regarding spring Quartz scheduled job in high availability configuration.

    If I were to deploy the spring application on 2 nodes and need the quartz scheduled job to run on only one node at any given time, then how can this be achieved.

    Thanks

    Reply
    1. If thing need to be in schedule mode, that means it’s not a “request on demand” thing. My advice is create a standalone scheduler project which only focus on scheduling, and put it on a dedicated server.

      Reply
  25. Java –

    3. Scheduler JobDetail
    
     RunMeTask task = new RunMeTask();
     
        	//specify your sceduler task details
        	JobDetail job = new JobDetail();
        	job.setName("runMeJob");
        	job.setJobClass(RunMeJob.class);
     
        	Map dataMap = job.getJobDataMap();
        	dataMap.put("runMeTask", task);
    

    i have done upto first 2 steps,,but in 3rd step,,where i have to put ur code of step 3 is it in step 2 class or i have to make a new class for step 3 code..,,,i m very new in java,,,so plz help me…

    thanks in advance

    Reply
    1. You can reference it with the “Full Example” section, or download the project and compare with yours.

      Reply
  26. Hi,

    can this code use for current time?
    i want to make my code run at 02:00 AM for example, can this code do this?

    Fast replay will be great, Thanks

    Reply
  27. I get this error, when I try to execute Quartz-Scheduler-Example\QuartzAppCronTrigger class file.

    Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.quartz.impl.StdSchedulerFactory.(StdSchedulerFactory.java:249)
    at com.mkyong.common.QuartzAppCronTrigger.main(QuartzAppCronTrigger.java:30)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    … 2 more

    I get following error when I am trying to update maven dependencies –
    9/19/11 11:35:43 AM IST: [WARN] The POM for opensymphony:quartz:jar:1.6.3 is missing, no dependency information available

    Thanks for your help in advance.

    Reply
  28. Can you please help me out? Can I able to schedule a Job which calls servlet and get data for me? (Actually this is my situation)
    Job—> calls—> servlet
    from there getting data back.
    Please please help me.I am struck here.

    Reply
      1. Probably when the article was written, JobDetail was a class. It is now an interface and cannot be used as described in step 3.

        Reply
        1. Exactly the problem being faced by me. I am just learning Quartz and it would be great if u could update this example using JobDetail as an Interface.

          Reply
  29. how to execute or fire directly the job Class without trigger the scheduler quartz?
    what if i just call the job class in other class?
    Thanks..

    Reply
    1. Do not get your use case, if your “Job Class” is not a scheduler job, why you need to use quartz?

      Nvm, you still can move all “Job Class” business logic into a new BO object, so that you can call it anywhere. Loosely coupled is always a good design pattern.

      Reply
    1. yes it is possible to get the timing of any job using getCronExpression method of Cron trigger.Jus specify the name of the job whose timing u want

      Reply
  30. Can you do DB queries with Quartz without using Spring? I get WARNING:

    “Using job-store ‘org.quartz.simpl.RAMJobStore’ – which does not support persistence. and is not clustered.”

    Reply
  31. Use the new dependency information…

    groupId – org.quartz-scheduler
    artifactId – quartz
    version – 1.7.3

    Reply
      1. ONE QUESTION – UR CODE SUGGEST –

        JobDetail job = new JobDetail(); => HOW DO YOU INSTANTIATE AN INTERFACE .. PLZ VERIFY

        Reply
        1. Quartz 2 APIs are big different with Quartz 1(1.5,1.6 and 1.7) Class JobDetail{
          }

          quartz-1.6.6:
          http://javasourcecode.org/html/open-source/quartz/quartz-1.6.6/org/quartz/JobDetail.html

          Quartz 2:
          public interface JobDetail extends Serializable, Cloneable {
          }

          // we have to create JobDetail in the below way.
          JobDetail job = newJob(HelloJob.class)

          // we have to create Trigger in the below way.
          Trigger trigger = newTrigger()

          Don’t foget to improt the below one
          import static org.quartz.JobBuilder.*;
          import static org.quartz.TriggerBuilder.*;

          Reply

          Reply
          1. Hi Mkyong,
            Is there any triggger which can be trigger on a key pressed(CTRL+SHIFT) in which we can execute the standanlone java .

Leave a Comment

Your email address will not be published. Required fields are marked *