Quartz定时调度器03

时间:2022-03-11 07:58:46
package com.demo.quartz.quartz01;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.TriggerKey;

public class HelloJob implements Job {

public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(new Date()));
JobKey jobKey=context.getJobDetail().getKey();
System.out.println("job : name is "+jobKey.getName()+ ", group is "+jobKey.getGroup());
TriggerKey triggerKey=context.getTrigger().getKey();
System.out.println("trigger : name is "+triggerKey.getName()+ ", group is "+triggerKey.getGroup());

JobDataMap jobDataMa=context.getJobDetail().getJobDataMap();
JobDataMap triggerDataMap=context.getTrigger().getJobDataMap();
String message=jobDataMa.getString("message");
String triggerMsg=triggerDataMap.getString("message");
System.out.println("job message is "+ message);
System.out.println("trigger message is "+ triggerMsg);

}

}
package com.demo.quartz.quartz01;import java.text.SimpleDateFormat;import java.util.Date;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SchedulerFactory;import org.quartz.SimpleScheduleBuilder;import org.quartz.Trigger;import org.quartz.TriggerBuilder;import org.quartz.impl.StdSchedulerFactory;public class HelloScheduler{public static void main(String[] args) throws SchedulerException{SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 创建JobDetail实例,将该实力和HelloJob绑定JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).usingJobData("message", "hello my job").withIdentity("myjob", "group1").build();// 创建Trigger实例,定义该job立即执行,并且每隔两秒执行一次,直到永远Trigger trigger = TriggerBuilder.newTrigger().usingJobData("message", "hello my trigger").withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();// 创建Scheduler实例SchedulerFactory schedulerFactory = new StdSchedulerFactory();Scheduler scheduler = schedulerFactory.getScheduler();scheduler.start();// 打印当前时间System.out.println(sf.format(new Date()));scheduler.scheduleJob(jobDetail, trigger);}}