Wednesday, March 9, 2016

How to Schedule a Job in Java in 3 easy steps.

How to Schedule a Job just like CronJob (in Java) in 3 easy steps ?

1)     Include Quartz dependency in pom.xml
<dependency>
           <groupId>opensymphony</groupId>
           <artifactId>quartz</artifactId>
           <version>1.6.3</version>
</dependency>

2)     Create a Job which needs to be run after fixed interval

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

public class TesttJob implements Job {
public void execute(JobExecutionContext context) {
System.out.println("Test Job running successfully");
}
}

3)     Create a CronTrigger which creates job object, trigger object and schedule it at the fixed interval.

public class CrontTriggerJob {
private static JobDetail testJob = null;
private static CronTrigger testTrigger = null;
    
public static void main(String[] args) throws ParseException, SchedulerException {

testJob = new JobDetail("dummyJobName","quartzJobGroup",TesttJob.class);

// Run after every 5 minutes        
testTrigger= new  CronTrigger("dummyCrontName","quartzJobGroup","0/5 * *   * * ?");
          
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(testJob, testTrigger);
}
}

No comments:

Post a Comment