My linux world » Java – Quartz

Java - Quartz


Contents

Dependencies

If you use maven, add this to your pom.xml :

<dependency>
  <groupId>org.quartz-scheduler</groupId>
  <artifactId>quartz</artifactId>
  <version>${quartz.version}</version>
</dependency>

Create a job

You class must implement org.quartz.Job:

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class LaunchTaskCron implements Job
{
  private static final Logger LOGGER = Logger.getLogger(LaunchTaskCron.class);
 
  public LaunchTaskCron()
  {
  LOGGER.info("LOADING LaunchTaskCron");
  }
 
  public void execute(JobExecutionContext context) throws JobExecutionException {
 
  JobDataMap jdm = context.getJobDetail().getJobDataMap();
  String szJobName = (String) jdm.get("jobName");
 
  try {
      // execute tests:
      String szTaskId = new Date().toString();
      jdm.put("taskId", szTaskId);
      LOGGER.info(String.format("Execution jobName: '%s' - taskId : '%s'", szJobName,szTaskId));      
 
    } catch (Exception e) {
      LOGGER.error(e.getMessage(),e);
    }
 
  }  
 
}

Cron

Create cron

// every 5 seconds:
String cronExpression = "0/5 * * * * ?";
 
if(CronExpression.isValidExpression(cronExpression)) {
  /// Data map:
  JobDataMap jdm = new JobDataMap();
  jdm.put("jobName", szJobName);
 
  // Build job:
  JobDetail job = JobBuilder.newJob(LaunchTaskCron.class).setJobData(jdm)
					.withIdentity(szJobName, DEFAULT_TRIGGER_GROUP).build();			
 
 
 // Build Trigger
 Trigger trigger = TriggerBuilder
			.newTrigger()
			.withIdentity(szJobName, "group")
			.withSchedule(
				CronScheduleBuilder.cronSchedule(cronExpression))
				.build();
 
// Schedule		
scheduler.scheduleJob(job, trigger);
}

Read Cron

String triggerName=jobName;
String triggerGroup=DEFAULT_TRIGGER_GROUP;
 
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
Trigger trigger = scheduler.getTrigger(triggerKey);

Update Cron

To update cron, you have to remove it and add it again :

removeFromCron(jobName);
addCron(jobName,cronExpression);

Delete Cron

String triggerName=jobName;
String triggerGroup=DEFAULT_TRIGGER_GROUP;
 
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
Trigger trigger = scheduler.getTrigger(triggerKey);
 
if(trigger != null){ 
  // job found, unschedule it:
  scheduler.unscheduleJob(triggerKey);
}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.