一、构建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-->
二、创建两个类
1、QuartzTest01.class
public class QuartzTest01 {
public static void main(String[] args) throws SchedulerException {
// 创建JobDetail作业信息
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withDescription("this is a test job")
.withIdentity("testJob","testGroup")
.build();
// 向任务传递数据
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("uname","张三");
jobDataMap.put("uage",16);
//任务运行的时间,SimpleSchedle 类型触发器有效
long time = System.currentTimeMillis() + 3 * 1000L; // 三秒后启动任务
Date startTime = new Date(time);
// 创建Trigger,使用SimpleScheduleBuilder 或者 CronScheduleBuilder
Trigger trigger = TriggerBuilder.newTrigger()
.withDescription("")
.withIdentity("ramTrigger", "ramTriggerGroup")
.startAt(startTime) //默认当前时间启动
//普通计时器
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(3))//间隔3秒,重复3次
//表达式计时器
//.withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?")) //3秒执行一次
.build();
// 创建Scheduler工厂
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// 从工厂中获取调度器实例
Scheduler scheduler = schedulerFactory.getScheduler();
//注册任务和定时器
scheduler.scheduleJob(jobDetail,trigger);
//启动 调度器
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("定时器任务执行:" + simpleDateFormat.format(date));
JobDataMap map=jobExecutionContext.getMergedJobDataMap();
System.out.println("参数值"+map.get("uname"));
System.out.println("參數值"+map.get("uage"));
}
}
网友评论