Quartz入门案例
Quartz依赖的jar包,pom如下:
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency>
Java代码程序入口如下如下:
1 package com.test.quartz; 2 3 import java.util.Date; 4 5 import org.quartz.CronScheduleBuilder; 6 import org.quartz.JobBuilder; 7 import org.quartz.JobDetail; 8 import org.quartz.Scheduler; 9 import org.quartz.Trigger; 10 import org.quartz.TriggerBuilder; 11 import org.quartz.impl.StdSchedulerFactory; 12 13 14 /** 15 * 任务调度入口类 16 * @author vince 17 * @version 1.0 18 */ 19 public class ScheduleEntrance { 20 21 //定时任务启动入口 22 public static void main(String[] args) { 23 try { 24 25 //创建scheduler 26 Scheduler scheduler = new StdSchedulerFactory().getScheduler(); 27 28 //当前时间 29 long time= System.currentTimeMillis() + 3 * 1000L; //几秒后启动任务 30 Date startTime = new Date(time); 31 32 //创建一个Trigger 33 Trigger trigger = TriggerBuilder.newTrigger() 34 .withDescription("This is a DS trigger.") 35 .withIdentity("DSTrigger", "DSTriggerGroup") 36 .startAt(startTime) 37 .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?")) 38 .build(); 39 40 //定义一个job 41 JobDetail jobDetail = JobBuilder.newJob(DSJob.class) 42 .withDescription("This is a DS job.") 43 .withIdentity("DSJob", "DSGroup") 44 .build(); 45 46 //注册任务和定时器 47 scheduler.scheduleJob(jobDetail, trigger); 48 49 //启动调度器 50 scheduler.start(); 51 52 } catch (Exception e) { 53 e.printStackTrace(); 54 } 55 } 56 57 }
Job类如下:
1 package com.test.quartz; 2 3 4 import org.quartz.Job; 5 import org.quartz.JobExecutionContext; 6 import org.quartz.JobExecutionException; 7 8 9 /** 10 * 数据同步任务类 11 * @author vince 12 * @version 1.0 13 */ 14 public class DSJob implements Job{ 15 16 @Override 17 public void execute(JobExecutionContext arg0) throws JobExecutionException { 18 19 System.out.println("------- Hello Quartz ! ------"); 20 21 } 22 23 }
执行结果: