一.
JobDetail可以为Job实例设置属性、jobDataMap属性等
JobExectionContext:Job的execute方法的参数,它记录了job的信息和Quartz相关的运行环境
JobDataMap:(1)进行任务调度室,JobDataMap存储在JobExectionContext中
(2)JobDataMap实现了java.util.Map接口
(3)Job实现类中添加setter方法对应的JobDataMap的键值,JobFactory实现类在初始化job实例对象时会自动调用这些setter方法
二.
Job类
/** * 需要实现Job接口 */ public class HelloJob implements Job { //Job实现类中添加setter方法对应的JobDataMap的键值,JobFactory实现类在初始化job实例对象时会自动调用这些setter方法 private Integer account; private String name; public void setAccount(Integer account) { this.account = account; } public void setName(String name) { this.name = name; } @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.now(); String localTime = df.format(time); System.out.println("数据库备份时间:"+localTime); JobKey key = jobExecutionContext.getJobDetail().getKey(); //通过JobExecutionContext类,我们可以在任务执行时获取Job本身的一些信息 System.out.println("任务:"+key.getGroup()+":"+key.getName()); //获取任务组和任务名称 System.out.println(jobExecutionContext.getJobDetail().getJobClass()); //获取Job的Class //获取任务数据的参数值 JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap(); dataMap.forEach((x,y)-> System.out.println(x+":"+y)); //Trigger和JobDetail类似,也可以传递dataMap(TriggerDataMap) //但是,如果遇到同名的key,trigger中的usingJobData会覆盖JobDetail中的usingJobData TriggerKey triggerKey = jobExecutionContext.getTrigger().getKey(); System.out.println("触发器:"+triggerKey.getGroup()+":"+triggerKey.getName()); //当前任务的执行时间 System.out.println("当前任务执行时间:"+jobExecutionContext.getFireTime()); //当前类的成员变量值 System.out.println("成员变量:"+account+":"+name); } }
main方法:
public static void main(String[] args) throws SchedulerException { //调度器(Scheduler) //从工厂中获取 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //任务数据 JobDataMap map = new JobDataMap(); map.put("account",123456); map.put("name","张三"); //任务实例(JobDetail) JobDetail jobDetail = JobBuilder.newJob(HelloJob.class) .withIdentity("job1", "group1") //参数一:任务名称 参数二:任务组 .usingJobData(map) //传递JobDataMap .build(); //触发器(Trigger) SimpleTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger1", "group1") .startNow()//立即启用 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(5)) //每5秒执行一次 .build(); //关联触发器和任务 按照触发器的条件执行任务 scheduler.scheduleJob(jobDetail,trigger); //启动 scheduler.start(); }
运行结果: