1.任務
Job:是一個接口,只有一個方法void execute(JobExecutionContext context),開發者實現該接口定義運行任務,JobExecutionContext類別提供了調度上下文的各種資訊。 Job運行時的資訊保存在 JobDataMap實例中;
2.觸發器
Trigger:是一個類,描述觸發Job執行的時間觸發規則。主要有SimpleTrigger和 CronTrigger這兩個子類別。當只需觸發一次或以固定時間間隔週期執行,SimpleTrigger是最適合的選擇;而CronTrigger則可以透過Cron表達式定義出各種複雜時間規則的調度方案:如每早晨9:00執行,週一、週三、週五下午5:00執行等;
3.調度器
JobDetail:Quartz在每次執行Job時,都重新建立一個Job實例,所以它不直接接受一個Job的實例,相反它接收一個Job實作類,以便在運行時透過newInstance()的反射機制實例化Job。因此需要透過一個類別來描述Job的實作類別及其它相關的靜態訊息,如Job名字、描述、關聯監聽器等訊息,JobDetail承擔了這個角色。
建立一個Quartz工作
1.計畫實體類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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;
}
}
|
登入後複製
2.提醒服務類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class RemindService {
public List<Plan> getPlansForToday(){
List<Plan> list= new ArrayList<Plan>();
Plan p1= new Plan( "2016-11-3" , "呵呵" );
Plan p2= new Plan( "2016-11-4" , "嘿嘿" );
list.add(p1);
list.add(p2);
return list;
}
public void ouputPlan(){
List<Plan> forToday = getPlansForToday();
for (Plan plan : forToday) {
System.out.println( "计划时间" +plan. getDate ()+ "计划内容" +plan.getTask());
}
}
}
|
登入後複製
3.提醒任務類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class RemindJob implements Job {
private RemindService service= new RemindService();
public void execute(JobExecutionContext arg0) throws JobExecutionException {
service.getPlansForToday();
}
public RemindService getService() {
return service;
}
public void setService(RemindService service) {
this.service = service;
}
}
|
登入後複製
4.調度定時器任務
3.提醒任務類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class TestJob {
public static void doRemind() throws SchedulerException, InterruptedException{
JobDetail job =JobBuilder.newJob(RemindJob. class ).withIdentity( "job1" , "group1" ).build();
Trigger trigger=TriggerBuilder.newTrigger().withIdentity( "myTrigger" , "group1" ).
withSchedule(CronScheduleBuilder.cronSchedule( "0 34 16 ? * 5#1 2016" )).build();
SchedulerFactory s= new StdSchedulerFactory();
Scheduler scheduler = s.getScheduler();
scheduler.scheduleJob(job,trigger);
scheduler.start();
}
public static void main(String[] args) throws SchedulerException, InterruptedException {
doRemind();
}
}
|
登入後複製
4.調度定時器任務
reee 