定时任务的触发有好几种模式,目前比较常用的是cronTrigger表达式和SimpleTrigger,下面是这两种实现方式的示例:
public class QuartzCronExample {
public static void main(String[] args) throws Exception {
//创建scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//启动scheduler
scheduler.start();
Class jobClass = Class.forName("com.alibaba.test.quartzdemo.HandleJobMsg");
//创建jobDetail实例
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity("jobName1", "jobGroup1").build();
JobDetail jobDetail1 = JobBuilder.newJob(jobClass).withIdentity("jobName2", "jobGroup2").build();
//创建CronTrigger
CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("jobName1", "jobGroup1")
.startNow()
.withSchedule(builder)
.build();
//创建SimpleTrigger
SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger()
.withIdentity("jobName2", "jobGroup2")
.startAt(new Date())//设置一个出发起始时间
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMilliseconds(10)//指定一个重复间隔,以毫秒为单位
.withRepeatCount(1000))//指定重复的次数
.build();
//执行调度
scheduler.scheduleJob(jobDetail, trigger);
scheduler.scheduleJob(jobDetail1, simpleTrigger);
Thread.sleep(10000L);
//停止scheduler
scheduler.shutdown();
}
}