Trigger是Quartz中的触发器,用来告诉调度器什么时候触发Job的执行。在Trigger的实例中可以定义触发Job的开始时间和结束时间等信息。
首先创建一个Job的实现类,在Job的实现类中获取Job的开始时间和结束时间
public class HelloJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sf.format(new Date());
Date startTime = context.getTrigger().getStartTime();
Date endTime = context.getTrigger().getEndTime();
System.out.println("Current Time : " + sf.format(new Date()));
System.out.println("Start Time : " + sf.format(startTime));
System.out.println("End Time : " + sf.format(endTime));
System.out.println("------------------------------------------");
}
}
创建测试方法,在测试中设置触发Job的开始时间和结束时间
public class TestHelloJob
{
public static void main( String[] args ) throws SchedulerException
{
/*创建JobDetail实例,并与HelloJob绑定;Job的名字是myjob,隶属于job_group组*/
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myjob", "job_group")
.build();
Date startTime = new Date();
Date endTime = new Date();
startTime.setTime(startTime.getTime() + 3000);
endTime.setTime(startTime.getTime() + 10000);
/*创建Trriger实例,指定在3秒后触发Job,10秒后结束Job, 每隔3秒钟执行一次*/
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("mytrigger", "trigger_group")
.startAt(startTime)
.endAt(endTime)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(3)
.repeatForever())
.build();
/*创建SchedulerFactory实例,把jobDetail与trigger绑定在一起*/
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
}
}
运行测试方法,输出日志如下
Current Time : 2018-04-01 23:17:42
Start Time : 2018-04-01 23:17:42
End Time : 2018-04-01 23:17:52
------------------------------------------
Current Time : 2018-04-01 23:17:45
Start Time : 2018-04-01 23:17:42
End Time : 2018-04-01 23:17:52
------------------------------------------
Current Time : 2018-04-01 23:17:48
Start Time : 2018-04-01 23:17:42
End Time : 2018-04-01 23:17:52
------------------------------------------
Current Time : 2018-04-01 23:17:51
Start Time : 2018-04-01 23:17:42
End Time : 2018-04-01 23:17:52
------------------------------------------
可见总共触发了4次Job