Quartz scheduler Example


This example show how to run Quartz with SimpleSchedule and CronSchedule. Quartz can download from official website

above image show project structure (this project used maven)

1. Add denpendency
add Quartz maven dependency in pom.xml

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.1.7</version>
        </dependency>

2. Create Job
create Quartz Job by implement Job

package com.example.quartz;

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

public class SimpleJob implements Job {

    public void execute(JobExecutionContext jec) throws JobExecutionException {
        System.out.println("doing simple job.");
    }
}

3. Create JobDetail
Create SimpleJob.java with detail

        JobDetail job = JobBuilder
                .newJob(SimpleJob.class)
                .withIdentity("SimpleJob")
                .build();

4. Create Trigger
Quartz has provide 2 type of trigger

  • SimpleTrigger (use SimpleScheduleBuilder)
  • CronTrigger (use CronScheduleBuilder)

Create SimpleSchedule

        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("SimpleJob")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                .build();

Create CronSchedule

        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("SimpleJob")
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .build();

5. Start Job
Job Start use Scheduler execute

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

Full source code

package com.example.quartz;

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;

public class SimpleSchedule 
{
    public static void main( String[] args ) throws SchedulerException
    {
        JobDetail job = JobBuilder
                .newJob(SimpleJob.class)
                .withIdentity("SimpleJob")
                .build();
        
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("SimpleJob")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                .build();
        
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job,trigger);
    }
}

Download Source From : Github



me on google plus+Jirawong Wongdokpuang

Quartz scheduler Example