package com.quartz.test1;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class HelloJob implements Job {
public HelloJob() throws SchedulerException, InterruptedException{
}
public void run() throws SchedulerException, InterruptedException{
// 1. 通过工厂得到 周期对象
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// 2. 创建触发器
Trigger trigger = TriggerBuilder
.newTrigger()
.withSchedule(
SimpleScheduleBuilder
.simpleSchedule()
.withIntervalInMilliseconds(2000L)//每两秒执行一次
.withRepeatCount(5)//执行5次
//.repeatForever() //无限执行
)
.build();
// 3. 创建 job
JobDetail detail = JobBuilder.newJob(HelloJob.class).build();
// 4. 注册 任务调度传入 detail, trigger
scheduler.scheduleJob(detail, trigger);
// 5.启动
scheduler.start();
}
//运行
public static void main(String[] args) throws SchedulerException, InterruptedException {
new HelloJob().run();
System.out.println("run");
}
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("date:" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}