1.Quartz架构图
1.实体层
package cn.happy.entity; //1. 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; } }
Plan实体类
2.服务层
package cn.happy.service; import java.util.ArrayList; import java.util.List; //2. import cn.happy.entity.Plan; public class RemindService { //0.2用来打印集合中提醒内容的方法 public void printMessage(){ List<Plan> list=getPlasnForToday(); for(Plan plan : list){ //单个的plan System.out.println("计划的时间"+plan.getDate()+"\t计划内容:"+plan.getTask()); } } //创建一个集合,并且方法返回值是一个集合类型 public List<Plan> getPlasnForToday(){ List<Plan> list=new ArrayList<Plan>(); Plan plan1=new Plan("2016年12月17日","月底可以买回家的车票!"); Plan plan2=new Plan("2016年12月17日","webservice"); list.add(plan2); list.add(plan1); return list; } }
RemindService
3.任务类的定义RemindJob implements Job
package cn.happy.quartz; import cn.happy.service.RemindService; //让一个普通类变成计划 public class RemindJob implements Job{ //植入service 对象 private RemindService service=new RemindService(); @Override public void execute(JobExecutionContext context)throws JobExecutionException{ service.printMessage(); } public RemindService getService() { return service; } public void setService(RemindService service) { this.service = service; } }
RemindJob
3.在Test类中综合咱们的计划和触发器
调度器≈Job+trigger
package cn.happy.test; import java.sql.Date; import cn.happy.quartz.RemindJob; public class MyQuertzTest { public static void tool() throws SchedulerException{ //第一步构建Job JobDetail job=JobBuilder.newJob(RemindJob.class)// .withIdentity("job1","group1")// .build(); //第二步构建Trigger /*Date runTime=DateBuilder.evenMinuteDate(new Date(System.currentTimeMillis())); Trigger trigger=TriggerBuilder.newTrigger().withIdentity("trigger1","group1")// .startAt(runTime).build();*/ /*Trigger trigger=TriggerBuilder.newTrigger()// .withIdentity(TriggerKey.triggerKey("myTrigger","myTriggerGroup"))// .withSchedule(SimpleScheduleBuilder.simpleSchedule()// //.withIntervalInMinutes(1)//一分钟出现一次 //.withIntervalInMilliseconds(2)//两毫秒出现一次 withIntervalInSeconds(2)//2秒出现一次 //.repeatForever()//可省略 )// .startAt(new Date(System.currentTimeMillis()+2000))// .build();*/ Trigger trigger=TriggerBuilder.newTrigger()// .withIdentity("myTrigger","myTriggerGroup")// .withSchedule(CronScheduleBuilder.cronSchedule("0 55 08 ? * 1#3 2016")).build(); //第三步绑定 Job 和 Trigger SchedulerFactory sf=new StdSchedulerFactory(); Scheduler sched=sf.getScheduler(); sched.scheduleJob(job,trigger); sched.start(); //Thread.sleep(3000);//睡眠3秒钟 sched.shutdown();//停止 } public static void main(String[] args) throws SchedulerException { tool(); System.out.println("aaaaaaaaa"); } }
测试类
总结:常用的Cron表达式
时间: 2024-08-01 19:28:54