Quartz è un framework che permette di schedulare processi da java.
Da questo link si può scaricare tutto il necessario.
Quartz Job
package com;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hello World Quartz Scheduler: " + new Date());
}
}Quartz Trigger
Definisce quando quartz deve eseguire il job://trigger il job ogni 5 secondi
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("helloTriggerName", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
.build();Scheduler
Linka il job con il trigger:// schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();scheduler.scheduleJob(job, trigger);Esempio Completo
HelloSchedule.javapackage com;import java.util.Date; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class HelloSchedule { public HelloSchedule() throws Exception { // JobDetail job = JobBuilder.newJob(HelloJob.class) .withIdentity("helloJobName", "group1").build(); //trigger il job ogni 5 secondi Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("helloTriggerName", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); // schedule it Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); scheduler.scheduleJob(job, trigger); } public static void main(String args[]) { try { new HelloSchedule(); } catch (Exception e) { } } }
EsecuzioneLanciando il main si ha l’esecuzione del job ogni 5 secondi: