导入依赖
<!--核心包--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
写一个类实现Job接口
public class HelloJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { //获得JobDetail对象 JobDetail jobDetail = context.getJobDetail(); JobKey key = jobDetail.getKey(); //获取标识 System.out.println(key.getName()); System.out.println(key.getGroup()); System.out.println("当前时间:"+new Date()); } }
写一个启动类
public class QuartzTest { public static void main(String[] args) throws SchedulerException { //创建一个scheduler调度器 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //创建一个Trigger触发器 Trigger trigger = TriggerBuilder.newTrigger()
//标识 .withIdentity("trigger1","group1") //每3秒中触发一次,一直触发 repeatForever //withRepeatCount 执行几次 .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever()) .build() ; //创建一个jobDetail JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1","group1").build(); //将jobDetail 和 触发器 增加到调度器中 scheduler.scheduleJob(job,trigger); //启动,调度器开启工作 scheduler.start(); } }