Sunday 28 July 2019

Quartz: Get the next fire time of the trigger after this time


Trigger interface provides 'getFireTimeAfter' method, it is used to get the next time at which the Trigger will fire, after the given time.

For example, below statements return tomorrows next fire time of the trigger.

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
Date nextFireTime = trigger1.getFireTimeAfter(tomorrow);
                 
System.out.println("Next fire time : " + nextFireTime);      

Find the below working application.

PrintJob.java
package com.sample.jobs;

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

public class PrintJob implements Job {
 public void execute(JobExecutionContext jec) throws JobExecutionException {
  System.out.println("Printing.....");
 }
}


QuartzSchedulerEx.java
package com.sample.app;

import java.util.Date;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;

import com.sample.jobs.PrintJob;

public class QuartzSchedulerEx {
 public static void main(String args[]) throws SchedulerException, InterruptedException {

  // Initiate a Schedule Factory
  SchedulerFactory schedulerFactory = new StdSchedulerFactory();
  // Retrieve a scheduler from schedule factory
  Scheduler scheduler = schedulerFactory.getScheduler();

  // Creating JobDetailImpl and link to our Job class
  JobDetailImpl printJobDetails = new JobDetailImpl();
  printJobDetails.setJobClass(PrintJob.class);
  printJobDetails.setName("PrintJob");
  printJobDetails.setGroup("PrintMessages");

  // Creating schedule time with trigger
  SimpleTriggerImpl trigger1 = new SimpleTriggerImpl();
  trigger1.setStartTime(new Date(System.currentTimeMillis() + 500));
  trigger1.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
  trigger1.setRepeatInterval(3000);
  trigger1.setName("First Trigger");
  trigger1.setDescription("Job executes every 1 second");

  // Start scheduler
  scheduler.start();

  // Schedule the jobs using triggers
  scheduler.scheduleJob(printJobDetails, trigger1);

  Date today = new Date();
  Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
  Date nextFireTime = trigger1.getFireTimeAfter(tomorrow);
  
  System.out.println("Next fire time : " + nextFireTime);

 }
}

You can able to see below messages in console.

Output
Next fire time : Fri Jul 20 10:47:26 IST 2018
Printing.....
Printing.....
Printing.....
Printing.....



Previous                                                    Next                                                    Home

No comments:

Post a Comment