調度任務框架Quart的使用_第1頁
調度任務框架Quart的使用_第2頁
調度任務框架Quart的使用_第3頁
調度任務框架Quart的使用_第4頁
調度任務框架Quart的使用_第5頁
已閱讀5頁,還剩8頁未讀, 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Cron表達式Quartz使用類似于Linux下的Cron表達式定義時間規則,Cron表達式由6或7個由空格分隔的時間字段組成,如表1所示:表1Cron表達式時間字段位置時間域名允許值允許的特殊字符1秒0-59,-*/2分鐘0-59,-*/3小時0-23,-*/4日期1-31,-*?/LWC5月份1-12,-*/6星期1-7,-*?/LC#7年(可選)空值1970-2099,-*/Cron表達式的時間字段除允許設置數值外,還可使用一些特殊的字符,提供列表、范圍、通配符等功能,細說如下:?星號(*):可用在所有字段中,表示對應時間域的每一個時刻,例如,*在分鐘字段時,表示''每分鐘”;?問號(?):該字符只在日期和星期字段中使用,它通常指定為''無意義的值”,相當于點位符;?減號(-):表達一個范圍,如在小時字段中使用“10-12”,則表示從10到12點,即10,11,12;?逗號(,):表達一個列表值,如在星期字段中使用“MON,WED,FRI”,則表示星期一,星期三和星期五;?斜杠(/):x/y表達一個等步長序列,x為起始值,y為增量步長值。如在分鐘字段中使用0/15,貝俵示為0,15,30和45秒,而5/15在分鐘字段中表示5,20,35,50,你也可以使用*/y,它等同于0/y;?L:該字符只在日期和星期字段中使用,代表“Last”的意思,但它在兩個字段中意思不同。L在日期字段中,表示這個月份的最后一天,如一月的31號,非閏年二月的28號;如果L用在星期中,則表示星期六,等同于7。但是,如果L出現在星期字段里,而且在前面有一個數值X,則表示''這個月的最后X天”,例如,6L表示該月的最后星期五;?W:該字符只能出現在日期字段里,是對前導日期的修飾,表示離該日期最近的工作日。例如15W表示離該月15號最近的工作日,如果該月15號是星期六,則匹配14號星期五;如果15日是星期日,則匹配16號星期一;如果15號是星期二,那結果就是15號星期二。但必須注意關聯的匹配日期不能夠跨月,如你指定1W,如果1號是星期六,結果匹配的是3號星期一,而非上個月最后的那天。W字符串只能指定單一日期,而不能指定日期范圍;LW組合:在日期字段可以組合使用LW,它的意思是當月的最后一個工作日;?井號(#):該字符只能在星期字段中使用,表示當月某個工作日。如6#3表示當月的第三個星期五(6表示星期五,#3表示當前的第三個),而4#5表示當月的第五個星期三,假設當月沒有第五個星期三,忽略不觸發;C:該字符只在日期和星期字段中使用,代表“Calendar”的意思。它的意思是計劃所關聯的日期,如果日期沒有被關聯,則相當于日歷中所有日期。例如5C在日期字段中就相當于日歷5日以后的第一天。1C在星期字段中相當于星期日后的第一天。Cron表達式對特殊字符的大小寫不敏感,對代表星期的縮寫英文大小寫也不敏感。表2下面給出一些完整的Cron表示式的實例:表2Cron表示式示例表示式說明"0012**?"每天12點運行"01510?**"每天10:15運行"01510**?"每天10:15運行"01510**?*"每天10:15運行"01510**?2008"在2008年的每天10:15運行"0*14**?"每天14點到15點之間每分鐘運行一次,開始于14:00,結束于14:59。"00/514**?"每天14點到15點每5分鐘運行一次,開始于14:00,結束于14:55。"00/514,18**?"每天14點到15點每5分鐘運行一次,此外每天18點到19點每5鐘也運行一次。"00-514**?"每天14:00點到14:05,每分鐘運行一次。"010,4414?3WED"3月每周三的14:10分到14:44,每分鐘運行一次。"01510?*MON-FRI"每周一,二,三,四,五的10:15分運行。"0151015*?"每月15日10:15分運行。"01510L*?"每月最后一天10:15分運行。"01510?*6L"每月最后一個星期五10:15分運行。"01510?*6L2007-2009"在2007,2008,2009年每個月的最后一個星期五的10:15分運行。"01510?*6#3"每月第三個星期五的10:15分運行。1.新建任務接口JobpublicinterfaceJob{publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException;}2?創建接口Job的實現類publicclassSimpleJobimplementsJob{publicvoidexecute(JobExecutionContextargO)throwsJobExecutionException{System.out.println("SimpleJob");〃執行內容}}調度任務執行建立要素.新建調度工廠SchedulerFactory對象sfSchedulerFactorysf=newStdSchedulerFactory();.獲取調度任務對象Schedulersched=sf.getScheduler();?幾種觸發開始時間設置Date startTime=org.quartz.DateBuilder.dateOf(int hour,intminute,intsecond,intdayOfMonth,intmonth,intyear)DatestartTime=org.quartz.DateBuilder.dateOf(inthour,intminute,intsecond)DatestartTime=newDate(System.currentTimeMillis()+60000L))/指定60秒鐘以后開始。DatestartTime=DateBuilder.nextGivenSecondDate(null,15);/每分鐘以15秒為單位,當前時間下個15秒開始DatestartTime=DateBuilder.nextGivenSecondDate(null,5);//每分鐘以5秒為單位,當前時間下個5秒開始DatestartTime=evenMinuteDate(newDate());〃當前時間下一分鐘開始DatestartTime=futureDate(5,IntervalUnit.SECOND);//當前時間加5秒開始DatestartTime=futureDate(5,IntervalUnit.MINUTE);//當前時間加5分鐘開始//IntervalUnit的屬性有(SECOND,MINUTE,HOUR,DAYWEEK,MONTH,YEAR)(4).新建任務job并設置一執行對象SimpleJob.class中execute()方法JobDetailjob=newJob(SimpleJob.class).withIdentity("job1","group1").build();新建觸發器并設置〃1.觸發一次atstartTimeSimpleTriggertrigger=(SimpleTrigger)newTrigger().withIdentity("trigger1","tgroup1")〃設置觸發器(名稱,組名)―全名.startAt(startTime)//設置開始時間.build();ft=sched.scheduleJob(job,trigger);〃2.先觸發1次atstartTime,再重復觸發10次,1次/10秒。如果10次內調度schedule關閉,也將提前終止。job=newJob(SimpleJob.class).withIdentity("job2","group1").build();trigger=newTrigger().withIdentity("trigger2","tgroup1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10)〃一次/10s.withRepeatCount(10))〃重復觸發共10次.build();ft=sched.scheduleJob(job,trigger);〃3.先觸發1次atstartTime,再重復一直觸發直到調度schedule關閉,1次/30秒。job=newJob(SimpleJob.class).withIdentity("job3","group1").build();trigger=newTrigger().withIdentity("trigger3","tgroup1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(30).repeatForever())〃一直重復觸發.build();ft=sched.scheduleJob(job,trigger);〃4.先觸發1次atstartTime,再重復觸發20次,1次/5分鐘。job=newJob(SimpleJob.class).withIdentity("job4","group1").build();trigger=newTrigger().withIdentity("trigger4","tgroup1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20)).build();ft=sched.scheduleJob(job,trigger);〃5.先觸發1次atstartTime,再重復觸發5次,1次/2小時。job=newJob(SimpleJob.class).withIdentity("job5","group1").build();trigger=newTrigger().withIdentity("trigger5","tgroup1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInHours(2).withRepeatCount(5)).build();ft=sched.scheduleJob(job,trigger);〃6?與上相同任務job5,創建另外觸發器trigger=newTrigger().withIdentity("trigger5","tgroup2").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(2)).forJob(job).build();ft=sched.scheduleJob(trigger);向調度中增加一對任務和觸發器返回調度觸發時間Dateft=sched.scheduleJob(job,trigger);調度開始啟動sched.start();設置調度關閉等待時間Thread.sleep(60L*1000L);//等待60秒,才進行下步。調度關閉,所有調度任務終止sched.shutdown(true);3?其他觸發器設置方法(計劃任務工具)〃觸發器1次/20秒CronTriggertrigger=newTrigger().withIdentity("trigger1","group1").withSchedule(cronSchedule("0/20****?")).build();〃觸發器1次/2分鐘,并在分鐘的第15秒開始trigger=newTrigger().withIdentity("trigger2","group1").withSchedule(cronSchedule("150/2***?")).build();〃觸發器1次/2分鐘,并在上午8點到下午5點之間開始trigger=newTrigger().withIdentity("trigger3","group1").withSchedule(cronSchedule("O0/28-17**?")).build();〃觸發器1次/3分鐘,并在下午5點到晚上11點之間開始trigger=newTrigger().withIdentity("trigger4","group1").withSchedule(cronSchedule("O0/317-23**?")).build();〃觸發器在每月1日到15日之間的10:00開始trigger=newTrigger().withIdentity("trigger5","group1").withSchedule(cronSchedule("O010am1,15*?")).build();〃觸發器1次/30秒,在Monday到Friday之間開始trigger=newTrigger().withIdentity("trigger6","group1").withSchedule(cronSchedule("0,30**?*MON-FRI")).build();〃觸發器1次/30秒,在Saturday,Sunday開始trigger=newTrigger().withIdentity("trigger7","groupl").withSchedule(cronSchedule("0,30**?*SAT,SUN")).build();其他方法介紹(l)JobExecutionContextcontext方法JobKeyjobKey=context.getJobDetail().getKey();JobDataMapdata=context.getJobDetail().getJobDataMap();⑵Job方法JobKeyjobkey=job.getKey();JobDataMapmap=job.getJobDataMap();Scheduler方法scheduler.clear()〃提供方便用于清除所有任務、觸發器和日程的方法scheduler.scheduleJobs(MapvJobDetail,ListvTrigger>>triggersAndJobs,booleanreplace)//方法可批量增加任務和觸發器scheduler.unscheduleJobs(ListvTriggerKey>triggerKeys)//方法提供批量取消任務的scheduler.deleteJobs(ListvJobKey>jobKeys)/批量刪除任務的scheduler.deleteJob(JobKeyjobKey)//刪除單個任務的scheduler.checkExists(JobKeyjobKey)和Scheduler.heckExists(TriggerKeytriggerKey)//提供用于檢測任務關鍵字的唯一性觸發器SimpleTrigge屬性設置方法SimpleTriggesimpleTrigge=(SimpleTrigger)newTrigger().withIdentity("trigger1","groupl")//設置觸發器(名稱,組名)-全名.startAt(startTime)//設置開始時間.EndAt(endTime)//設置結束時間.withRepeatCount()〃獲取觸發器重復次數.withRepeatInterval()//1000獲取觸發器重復觸發間隔時間秒.repeatForever()〃永久重復觸發.build();(5)觸發器CronTrigger屬性設置方法CronTriggertrigger=newTrigger().withIdentity("trigger1","groupl").withSchedule(cronSchedule("0/20****?"))//觸發器1次/20秒.build();(6)其他方法Thread.sleep(30L*1000L);/等待30秒,才進行下步。5?調度與任務之間傳遞參數--例如(1)任務job--ColorJob代碼;publicclassColorJobimplementsJob{publicstaticfinalStringFA/ORITE_COLOR="favoritecolor";publicstaticfinalStringEXECUTION_COUNT="count";publicstaticint_counter=1;publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{JobKeyjobKey=context.getJobDetail().getKey();JobDataMapdata=context.getJobDetail().getJobDataMap();StringfavoriteColor=data.getString(FA/ORITE_COLOR);intcount=data.getInt(EXECUTION_COUNT);("ColorJob:"+jobKey+"executingat"+newDate()+"\n"+"favoritecoloris"+favoriteColor+"\n"+"executioncount(fromjobmap)is"+count+"\n"+"executioncount(fromjobmembervariable)is"+_counter++);count++;data.put(EXECUTION_COUNT,count);}}(2)調度中相應設置部分代碼DatestartTime=nextGivenSecondDate(null,10);//job1willonlyrun5times(atstarttime,plus4repeats),every10secondsJobDetailjob1=newJob(ColorJob.class).withIdentity("jobl","groupl").build();SimpleTriggertriggerl=newTrigger().withIdentity("triggerl","group1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();//passinitializationparametersintothejob--對任務的參數初始化job1.getJobDataMap().put(ColorJob.FA/ORITE_COLOR,"Green");job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT,1);//schedulethejobtorunDatescheduleTime1=sched.scheduleJob(job1,trigger1);6.觸發器中日歷Calendar使用〃法定節日是以每年為周期的,所以使用AnnualCalendar//AddtheholidaycalendartothescheduleAnnualCalendarholidays=newAnnualCalendar();//fourthofJuly(July4)CalendarfourthOfJuly=newGregorianCalendar(2012,6,4);holidays.setDayExcluded(fourthOfJuly,true);//true排除的日期,如果設置為false則為包含//halloween(Oct31)Calendarhalloween=newGregorianCalendar(2012,9,31);holidays.setDayExcluded(halloween,true);//christmas(Dec25)Calendarchristmas=newGregorianCalendar(2012,10,24);holidays.setDayExcluded(christmas,true);//tellthescheduleaboutourholidaycalendarsched.addCalendar("holidays",holidays,false,false);//向Scheduler注冊日歷//scheduleajobtorunhourly,startingonhalloween//at10am//DaterunDate=DateBuilder.dateOf(11,46,10);DaterunDate=DateBuilder.nextGivenSecondDate(null,10);JobDetailjob=newJob(SimpleJob.class).withIdentity("job1","group1").build();SimpleTriggertrigger=newTrigger().withIdentity("trigger1","group1").startAt(runDate).withSchedule(simpleSchedule().withIntervalInHours(1).repeatForever()).modifiedByCalendar("holidays").build();//schedulethejobandprintthefirstrundateDatefirstRunTime=sched.scheduleJob(job,trigger);7?監聽器的使用(1)新建SimpleJob1代碼如下importjava.util.Date;importorg.quartz.Job;importorg.quartz.JobExecutionContext;importorg.quartz.JobExecutionException;importorg.quartz.JobKey;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassSimpleJoblimplementsJob{privatestaticLogger_log=LoggerFactory.getLogger(SimpleJob1.class);/***Emptyconstructorforjobinitilization*/publicSimpleJob1(){}publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{//Thisjobsimplyprintsoutitsjobnameandthe//dateandtimethatitisrunningJobKeyjobKey=context.getJobDetail().getKey();("SimpleJob1says:"+jobKey+"executingat"+newDate());}}(2)新建SimpleJob2代碼如下importjava.util.Date;importorg.quartz.Job;importorg.quartz.JobExecutionContext;importorg.quartz.JobExecutionException;importorg.quartz.JobKey;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassSimpleJob2implementsJob{privatestaticLogger_log=LoggerFactory.getLogger(SimpleJob2.class);/***Emptyconstructorforjobinitilization*/publicSimpleJob2(){}publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{//Thisjobsimplyprintsoutitsjobnameandthe//dateandtimethatitisrunningJobKeyjobKey=context.getJobDetail().getKey();("SimpleJob2says:"+jobKey+"executingat"+newDate());}}(3)創建監聽器接口JobListener的實現類JoblListener,當調度觸發任務SimpleJobl時,執行此監聽器并把SimpleJob2注冊到調度中。importstaticorg.quartz.JobBuilder.newJob;importstaticorg.quartz.TriggerBuilder.newTrigger;importorg.quartz.JobDetail;importorg.quartz.JobExecutionContext;importorg.quartz.JobExecutionException;importorg.quartz.JobListener;importorg.quartz.SchedulerException;importorg.quartz.SimpleTrigger;importorg.quartz.Trigger;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassJob1ListenerimplementsJobListener{privatestaticLogger_log=LoggerFactory.getLogger(Job1Listener.class);publicStringgetName(){return"job1_to_job2";}publicvoidjobToBeExecuted(JobExecutionContextinContext){("Job1Listenersays:JobIsabouttobeexecuted.");}publicvoidjobExecutionVetoed(JobExecutionContextinContext){("JoblListenersays:JobExecutionwasvetoed.");}publicvoidjobWasExecuted(JobExecutionContextinContext,JobExecutionExceptioninException){("Job1Listenersays:Jobwasexecuted.");//Simplejob#2JobDetailjob2=newJob(SimpleJob2.class).withIdentity("job2").build();Triggertrigger=(SimpleTrigger)newTrigger().withIdentity("job2Trigger").startNow().build();try{//schedulethejobtorun!inContext.getScheduler().scheduleJob(job2,trigger);}catch(SchedulerExceptione){」og.warn("Unabletoschedulejob2!");e.printStackTrace();}}}(4)創建調度程序,把監聽器Job1Listener綁定到任務SimpleJob1的觸發事件中。importstaticorg.quartz.JobBuilder.newJob;importstaticorg.quartz.SimpleScheduleBuilder.simpleSchedule;importstaticorg.quartz.TriggerBuilder.newTrigger;importjava.util.Date;importorg.quartz.JobDetail;importorg.quartz.JobKey;importorg.quartz.JobListener;importorg.quartz.ListenerManager;importorg.quartz.Matcher;importorg.quartz.Scheduler;importorg.quartz.SchedulerFactory;importorg.quartz.SchedulerMetaData;importorg.quartz.SimpleTrigger;importorg.quartz.Trigger;importorg.quartz.impl.StdSchedulerFactory;importorg.quartz.impl.matchers.KeyMatcher;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;/**Demonstratesthebehaviorofvcode>JobListenerv/code>s.Inparticular,thisexamplewilluseajoblistenertotriggeranotherjobafteronejobsuccesfullyexecutes.**/publicclass

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論