首页 > 代码库 > Quartz
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。