一开仰、構(gòu)建maven項目
1丧裁、在pom.xml中引入jar包
<!--引入quartz依賴-->
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.0</version>
</dependency>
<!--引入quartz依賴 END-->
二讼撒、創(chuàng)建兩個類
1再菊、QuartzTest01.class
public class QuartzTest01 {
public static void main(String[] args) throws SchedulerException {
// 創(chuàng)建JobDetail作業(yè)信息
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withDescription("this is a test job")
.withIdentity("testJob","testGroup")
.build();
// 向任務(wù)傳遞數(shù)據(jù)
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("uname","張三");
jobDataMap.put("uage",16);
//任務(wù)運行的時間,SimpleSchedle 類型觸發(fā)器有效
long time = System.currentTimeMillis() + 3 * 1000L; // 三秒后啟動任務(wù)
Date startTime = new Date(time);
// 創(chuàng)建Trigger宏邮,使用SimpleScheduleBuilder 或者 CronScheduleBuilder
Trigger trigger = TriggerBuilder.newTrigger()
.withDescription("")
.withIdentity("ramTrigger", "ramTriggerGroup")
.startAt(startTime) //默認當(dāng)前時間啟動
//普通計時器
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(3))//間隔3秒训裆,重復(fù)3次
//表達式計時器
//.withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?")) //3秒執(zhí)行一次
.build();
// 創(chuàng)建Scheduler工廠
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// 從工廠中獲取調(diào)度器實例
Scheduler scheduler = schedulerFactory.getScheduler();
//注冊任務(wù)和定時器
scheduler.scheduleJob(jobDetail,trigger);
//啟動 調(diào)度器
scheduler.start();
}
}
2.MyJob.class
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("定時器任務(wù)執(zhí)行:" + simpleDateFormat.format(date));
JobDataMap map=jobExecutionContext.getMergedJobDataMap();
System.out.println("參數(shù)值"+map.get("uname"));
System.out.println("參數(shù)值"+map.get("uage"));
}
}