Quartz是一个完全由Java编写的开源作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制。Quartz允许开发人员根据时间间隔来调度作业。它实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。
先来看一个简单的Quartz应用,让它每隔5s打印"Hello, Quartz",打印10次。
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloQuartzJob implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println( "Hello, Quartz! - executing its JOB at " +
new Date() + " by " + context.getTrigger().getName());
}
}
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloQuartzJob implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println( "Hello, Quartz! - executing its JOB at " +
new Date() + " by " + context.getTrigger().getName());
}
}
import java.sql.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class HelloQuartzScheduling {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail jobDetail = new JobDetail( "helloQuartzJob",
Scheduler.DEFAULT_GROUP, HelloQuartzJob. class);
SimpleTrigger simpleTrigger = new SimpleTrigger( "simpleTrigger",
Scheduler.DEFAULT_GROUP);
simpleTrigger.setStartTime( new Date(System.currentTimeMillis()));
simpleTrigger.setRepeatInterval( 5000);
simpleTrigger.setRepeatCount( 10);
scheduler.scheduleJob(jobDetail, simpleTrigger);
scheduler.start();
}
}
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class HelloQuartzScheduling {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail jobDetail = new JobDetail( "helloQuartzJob",
Scheduler.DEFAULT_GROUP, HelloQuartzJob. class);
SimpleTrigger simpleTrigger = new SimpleTrigger( "simpleTrigger",
Scheduler.DEFAULT_GROUP);
simpleTrigger.setStartTime( new Date(System.currentTimeMillis()));
simpleTrigger.setRepeatInterval( 5000);
simpleTrigger.setRepeatCount( 10);
scheduler.scheduleJob(jobDetail, simpleTrigger);
scheduler.start();
}
}