Quartz定时器使用比价广泛,介绍一点简单的使用
上代码:
定义一个Job,执行具体的任务
package org.tonny.quartz; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { /** * 执行具体的任务 */ // 获取传递的参数 Object param = context.getJobDetail().getJobDataMap().get("data"); System.out.println(format(param.toString())); } /** * 格式化输出, * * @param info * @return */ private String format(String info) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date); return String.format("%s: The result is %s", time, info); } }
Job的执行
package org.tonny.quartz; import java.util.HashMap; import java.util.Map; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; 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 Exception { // 创建一个JobDetail实例,将该实例与HelloJob Class绑定 JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("HelloJob", "HelloGroup").build(); Map<String, Object> data = new HashMap<String, Object>(); data.put("hello", "quartz"); jobDetail.getJobDataMap().put("data", data); // 创建一个Trigger实例,定义该Job立即执行,并且每隔2秒执行一次 // 注意Trigger中的HelloGroup与JobDetail中虽然名字相同,但两个是不一样的,因为在不同的类空间 Trigger trigger = TriggerBuilder.newTrigger(). withIdentity("HelloTrigger", "HelloGroup") .withSchedule(SimpleScheduleBuilder .simpleSchedule() .withIntervalInSeconds(2) .repeatForever()) .startNow().build(); // 创建scheduler实例 SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); // 将job和触发器进行关联 scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); try {// 主线程等待 Thread.sleep(300000L); } catch (Exception e) { e.printStackTrace(); } // 关闭调度器 scheduler.shutdown(true); } }
好了就这样吧
时间: 2024-10-13 12:25:00