Quartz
Posted 李泽阳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Quartz相关的知识,希望对你有一定的参考价值。
所需架包
第一步:创建entity类
package cn.happy.entity; public class Plan { private String date; //时间 private String task; //任务 public Plan(String date, String task) { this.date = date; this.task = task; } public Plan() { } @Override public String toString() { return "Plan [date=" + date + ", task=" + task + "]"; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } }
第二步:创建quartz
package cn.happy.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import cn.happy.service.RemindService; public class RemindJob implements Job { private RemindService service=new RemindService(); @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { service.printMessage(); } public RemindService getService() { return service; } public void setService(RemindService service) { this.service = service; } }
第三步:创建service
package cn.happy.service; import java.util.ArrayList; import java.util.List; import cn.happy.entity.Plan; public class RemindService { public List<Plan> getPlansforToday(){ List<Plan> list=new ArrayList<Plan>(); Plan plan1=new Plan("2016-12-17 23:02:32","Study makes me happy!!"); Plan plan2=new Plan("2016-12-17 23:02:50","Really!!"); list.add(plan1); list.add(plan2); return list; } public void printMessage(){ List<Plan> list=getPlansforToday(); for (Plan plan : list) { System.out.println("计划的时间:"+plan.getDate()+"计划的内容:"+plan.getTask()); } } }
第四步:创建测试类
package cn.happy.test; import java.util.Date; 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; import cn.happy.quartz.RemindJob; public class MyQuartzTest { public static void tool() throws Exception{ //创建job JobDetail job = JobBuilder.newJob(RemindJob.class)// .withIdentity("job1", "group1").build(); //构建trigger Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("myTrigger", "myTriggerGroup") .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(3) .repeatForever()) .startAt(new Date(System.currentTimeMillis())) .build(); //创建调度者工厂 SchedulerFactory sfc = new StdSchedulerFactory(); //创建一个调度者 Scheduler sched=sfc.getScheduler(); //注册并进行调度 sched.scheduleJob(job, trigger); sched.start(); //Thread.sleep(3000); } public static void main(String[] args) { try { tool(); } catch (Exception e) { e.printStackTrace(); } System.out.println("aa"); } }
每隔三秒输出一次
以上是关于Quartz的主要内容,如果未能解决你的问题,请参考以下文章
一行代码完成定时任务调度,基于Quartz的UI可视化操作组件 GZY.Quartz.MUI
我在java项目中加了spring支持,加了quartz-1.6.1.jar包,在使用quartz实现任务调用时的代码如下: