1.定义任务执行者
2.构造任务、调度任务
/**
26 * job service implements
27 * User: luowei
28 * Date: 12-7-8
29 * Time: 下午12:58
30 */
31 @Service("jobService")
32 public class JobServiceImpl implements JobService {
33
34 @Autowired
35 NewestMusicService newestMusicService;
36
37 @Autowired
38 HotestMusicService hotestMusicService;
39
40 //最新任务的名称
41 private static String getNewestJobDetailName = null;
42 //最新触发器的名称
43 private static String getNewestTriggerName = null;
44 //最新任务组
45 private static String getNewestGroup = "getNewestGroup";
46
47 /**
48 * 获取最新的任务
49 * @return 加载任务的时间
50 */
51 public Date getNewestJob(){
52
53 //调度时间
54 Date schelderDate = null;
55
56 //任务
57 JobDetail job = null;
58 String jobName = DateUtil.getYYYYMMDDHHMMSS(Calendar.getInstance().getTime())+"_getNewestJob";
59 if(getNewestJobDetailName == null){
60 job = JobUtil.initDurableJob(getNewestGroup, jobName, NewestJob.class);
61 }
62 Map<String,Object> map = new HashMap<String, Object>();
63 map.put(NewestJob.SERVICE,newestMusicService);
64 JobUtil.setData2Job(job,map);
65
66 //触发器
67 Trigger trigger = null;
68 String triName = DateUtil.getYYYYMMDDHHMMSS(Calendar.getInstance().getTime())+"_getNewestTrigger";
69 Date startTime = DateUtils.parseDate(ConfigUtil.getConfigMap().get(FinalConfig.GET_NEWEST_STARTTIME).getValue());
70 Integer intervalInHours = Integer.valueOf(ConfigUtil.getConfigMap().get(FinalConfig.NEWEST_INTERVALINHOURS).getValue());
71 if(startTime!=null && intervalInHours!=null){
72 trigger = JobUtil.initMinuteRepeatTrigger(getNewestGroup,triName,startTime,intervalInHours);
73 }
74
75 //调度任务
76 if(getNewestTriggerName == null){
77 schelderDate = JobUtil.runJob(job,trigger);
78 }else {
79 TriggerKey triggerKey = JobUtil.triggerKeyMap.get(getNewestTriggerName);
80 schelderDate = JobUtil.reSchedulerJob(triggerKey,trigger);
81 }
82
83 //给名称赋值
84 getNewestJobDetailName = jobName;
85 getNewestTriggerName = triName;
86 return schelderDate;
87 }
186 …………
187
188 }
3.封装类
JobUtil.java |
1 package com.ttpod.musicSNS.util;
3 import org.apache.commons.lang.StringUtils;
5 import org.quartz.impl.StdSchedulerFactory;
6 import org.quartz.impl.matchers.GroupMatcher;
8 import org.slf4j.LoggerFactory;
18 protected static Logger logger = (Logger) LoggerFactory.getLogger(JobUtil.class);
21 * define a scheduler ,will be a sington instance
23 private static Scheduler scheduler = null;
26 * get the name with default name 'QuartzScheduler' scheduler
29 public static Scheduler getScheduler(){
31 SchedulerFactory schedulerFactory = new StdSchedulerFactory();
33 scheduler = schedulerFactory.getScheduler();
34 } catch (SchedulerException e) {
35 logger.error(e.getMessage(),e);
42 * get the scheduler with named shcedulerName
46 public static Scheduler getScheduler(String schedulerName){
48 SchedulerFactory schedulerFactory = new StdSchedulerFactory();
50 scheduler = schedulerFactory.getScheduler(schedulerName);
51 } catch (SchedulerException e) {
52 logger.error(e.getMessage(),e);
59 * scheduler a job with specefied trigger
64 public static Date schedulerAJobWithTrigger(JobDetail job,Trigger trigger){
67 scheduler = getScheduler();
70 if(!scheduler.checkExists(job.getKey())
71 && !scheduler.checkExists(trigger.getKey())){
72 date = scheduler.scheduleJob(job,trigger);
74 } catch (SchedulerException e) {
75 logger.error(e.getMessage(),e);
81 * Remove (delete) the <code>{@link org.quartz.Trigger}</code> with the
82 * given key, and store the new given one - which must be associated
83 * with the same job (the new trigger must have the job name & group specified)
84 * - however, the new trigger need not have the same name as the old trigger.
86 * @param triggerKey identity of the trigger to replace
88 * The new <code>Trigger</code> to be stored.
90 * @return <code>null</code> if a <code>Trigger</code> with the given
91 * name & group was not found and removed from the store (and the
92 * new trigger is therefore not stored), otherwise
93 * the first fire time of the newly scheduled trigger is returned.
95 public static Date reSchedulerJob(TriggerKey triggerKey,Trigger newTrigger){
98 if(triggerKey != null && newTrigger != null && scheduler.isStarted())
99 date = scheduler.rescheduleJob(triggerKey,newTrigger);
100 triggerKeyMap.remove(triggerKey.getName());
101 } catch (SchedulerException e) {
102 logger.error(e.getMessage(),e);
108 * scheduler a job with specefied trigger in a specefied shceduler
114 public static Date schedulerAJobWithTrigger(String schedulerName,JobDetail job,Trigger trigger){
117 scheduler = getScheduler(schedulerName);
120 if(!scheduler.checkExists(job.getKey())
121 && scheduler.checkExists(trigger.getKey())){
122 date = scheduler.scheduleJob(job,trigger);
124 } catch (SchedulerException e) {
125 logger.error(e.getMessage(),e);
134 public static Boolean startScheduler(){
138 scheduler = getScheduler();
140 if(!scheduler.isStarted()){
145 } catch (SchedulerException e) {
146 logger.error(e.getMessage(),e);
155 public static Boolean shutdownScheduler(){
157 if(scheduler != null && !scheduler.isShutdown()){
161 } catch (SchedulerException e) {
162 logger.error(e.getMessage(),e);
170 public static Map<String,TriggerKey> triggerKeyMap = new HashMap<String,TriggerKey>();
173 * get a trigger which will repeat forever with in every other specified hours
174 * @param groupName group name
175 * @param triggerName trigger name
176 * @param startTime start time
177 * @param intervalInHours interval in minutes
178 * @return the updated SimpleScheduleBuilder
180 public static Trigger initHourRepeatTrigger(String groupName,String triggerName,
181 Date startTime,Integer intervalInHours){
182 SimpleTrigger trigger = null;
183 if(StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(triggerName)
184 && startTime!=null && intervalInHours!=null){
185 trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
186 .withIdentity(triggerName,groupName)
187 .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(intervalInHours))
189 triggerKeyMap.put(triggerName, trigger.getKey());
195 * get a trigger which will repeat forever with in every other specified minutes
196 * @param groupName group name
197 * @param triggerName trigger name
198 * @param startTime start time
199 * @param intervalInMinutes interval in minutes
200 * @return the updated SimpleScheduleBuilder
202 public static Trigger initMinuteRepeatTrigger(String groupName,String triggerName,
203 Date startTime,Integer intervalInMinutes){
204 SimpleTrigger trigger = null;
205 if(StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(triggerName)
206 && startTime!=null && intervalInMinutes!= null){
207 trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
208 .withIdentity(triggerName,groupName)
210 .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(intervalInMinutes))
212 triggerKeyMap.put(triggerName, trigger.getKey());
218 * get a trigger which will repeat forever with every other specified seconds
219 * @param groupName group name
220 * @param triggerName trigger name
221 * @param startTime start time
222 * @param intervalInSeconds interval in seconds
225 public static Trigger initSecondRepeatTrigger(String groupName,String triggerName,
226 Date startTime,Integer intervalInSeconds){
227 SimpleTrigger trigger = null;
228 if(StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(triggerName)
229 && startTime!=null && intervalInSeconds!=null){
230 trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
231 .withIdentity(triggerName,groupName)
233 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(intervalInSeconds))
236 triggerKeyMap.put(triggerName, trigger.getKey());
241 * set to repeat the given number of times - 1 with an interval of the given number of seconds.
242 * Note: Total count = 1 (at start time) + repeat count
243 * @param groupName group name
244 * @param triggerName trigger name
245 * @param startTime start time
250 public static Trigger initRepeatCountTrigger(String groupName,String triggerName,
251 Date startTime,Integer count,Integer seconds){
252 SimpleTrigger trigger = null;
253 if(StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(triggerName)
254 && startTime!=null && count!=null && seconds!=null){
255 trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
256 .withIdentity(triggerName,groupName)
258 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(count,seconds))
260 triggerKeyMap.put(triggerName, trigger.getKey());
266 * Create a CronTrigger with the given cron-expression string - which
267 * is presumed to b e valid cron expression (and hence only a RuntimeException
268 * will be thrown if it is not).
275 public static Trigger initCronTrigger(String groupName,String triggerName,
276 Date startTime,String cronExpression){
277 CronTrigger trigger = null;
278 if(StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(triggerName)
279 && StringUtils.isNotBlank(cronExpression) && startTime!=null){
280 trigger = (CronTrigger)TriggerBuilder.newTrigger()
281 .withIdentity(triggerName,groupName)
283 .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
285 triggerKeyMap.put(triggerName, trigger.getKey());
290 public static Map<String,JobKey> jobKeyMap = new HashMap<String,JobKey>();
293 * init a job with the specified jobName,groupName and clazz
300 public static JobDetail initJob(String groupName, String jobName, Class<? extends Job> clazz){
302 if(StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(groupName) && clazz!=null){
303 job = JobBuilder.newJob((Class<? extends Job>) clazz)
304 .withIdentity(jobName,groupName)
306 jobKeyMap.put(jobName, job.getKey());
318 public static JobDetail initDurableJob(String groupName, String jobName, Class<? extends Job> clazz){
320 if(StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(groupName) && clazz!=null){
321 job = JobBuilder.newJob((Class<? extends Job>) clazz)
322 .withIdentity(jobName,groupName)
325 jobKeyMap.put(jobName, job.getKey());
331 * add data to JobDetail,which data were stored in map
332 * @param jobDetail jobDetail
336 public static Boolean setData2Job(JobDetail jobDetail,Map<? extends String,? extends Object> map){
337 if(jobDetail!=null && map!=null){
338 jobDetail.getJobDataMap().putAll(map);
346 * add data to Trigger,which data were stored in map
351 public static Boolean setData2Trigger(Trigger trigger,Map<? extends String,? extends Object> map) {
352 if(trigger!=null && map!=null){
353 trigger.getJobDataMap().putAll(map);
361 * delete a job with specified jobName,this oporater will delete the job from Scheduler,
362 * and remove the Entry Element which key equals jobName from global varible jobkeyMap
366 public static Boolean delJob(String jobName){
368 if(StringUtils.isNotBlank(jobName)){
369 JobKey jobKey = jobKeyMap.get(jobName);
371 scheduler.deleteJob(jobKey);
372 jobKeyMap.remove(jobName);
374 } catch (SchedulerException e) {
375 logger.error(e.getMessage(),e);
383 * delete all jobs,this oporater will delete the job from Scheduler,
384 * and remove the Entry Element which key equals jobName from global varible jobkeyMap
387 public static Boolean delAllJob(){
390 List<JobKey> jobKeyList = new ArrayList<JobKey>();
391 jobKeyList.addAll(jobKeyMap.values());
392 scheduler.deleteJobs(jobKeyList);
395 } catch (SchedulerException e) {
396 logger.error(e.getMessage(),e);
403 * Resume (un-pause) the <code>{@link org.quartz.JobDetail}</code> with
407 * If any of the <code>Job</code>'s<code>Trigger</code> s missed one
408 * or more fire-times, then the <code>Trigger</code>'s misfire
409 * instruction will be applied.
414 public static Boolean pauseJob(String jobName){
416 if(StringUtils.isNotBlank(jobName)){
417 JobKey jobKey = jobKeyMap.get(jobName);
419 scheduler.pauseJob(jobKey);
421 } catch (SchedulerException e) {
422 logger.error(e.getMessage(),e);
430 * Resume (un-pause) the <code>{@link org.quartz.JobDetail}</code> with
434 * If any of the <code>Job</code>'s<code>Trigger</code> s missed one
435 * or more fire-times, then the <code>Trigger</code>'s misfire
436 * instruction will be applied.
442 public static Boolean resumeJob(String jobName){
444 if(StringUtils.isNotBlank(jobName)){
445 JobKey jobKey = jobKeyMap.get(jobName);
447 scheduler.resumeJob(jobKey);
449 } catch (SchedulerException e) {
450 logger.error(e.getMessage(),e);
458 * Remove the indicated <code>{@link Trigger}</code> from the scheduler.
460 * <p>If the related job does not have any other triggers, and the job is
461 * not durable, then the job will also be deleted.</p>
463 public static Boolean unscheduleJob(String triggerName){
465 if(StringUtils.isNotBlank(triggerName)){
466 TriggerKey triggerKey = triggerKeyMap.get(triggerName);
468 scheduler.unscheduleJob(triggerKey);
470 } catch (SchedulerException e) {
471 logger.error(e.getMessage(),e);
479 * Remove all of the indicated <code>{@link Trigger}</code>s from the scheduler.
481 * <p>If the related job does not have any other triggers, and the job is
482 * not durable, then the job will also be deleted.</p>
484 * <p>Note that while this bulk operation is likely more efficient than
485 * invoking <code>unscheduleJob(TriggerKey triggerKey)</code> several
486 * times, it may have the adverse affect of holding data locks for a
487 * single long duration of time (rather than lots of small durations
490 public static Boolean unscheduleJobs(){
493 List<TriggerKey> triggerKeyList = new ArrayList<TriggerKey>();
494 triggerKeyList.addAll(triggerKeyMap.values());
495 scheduler.unscheduleJobs(triggerKeyList);
497 } catch (SchedulerException e) {
498 logger.error(e.getMessage(),e);
505 * delete a trigger with specified triggerName,this operate will delete the job from Scheduler,
506 * and remove the Entry Element which key equals jobName from global varible jobkeyMap
510 public static Boolean pauseTrigger(String triggerName){
512 if(StringUtils.isNotBlank(triggerName)){
513 TriggerKey triggerKey = triggerKeyMap.get(triggerName);
515 scheduler.pauseTrigger(triggerKey);
517 } catch (SchedulerException e) {
518 logger.error(e.getMessage(),e);
526 * Resume (un-pause) the <code>{@link Trigger}</code> with the given
530 * If the <code>Trigger</code> missed one or more fire-times, then the
531 * <code>Trigger</code>'s misfire instruction will be applied.
536 public static Boolean resumeTrigger(String triggerName){
538 if(StringUtils.isNotBlank(triggerName)){
539 TriggerKey triggerKey = triggerKeyMap.get(triggerName);
541 scheduler.resumeTrigger(triggerKey);
543 } catch (SchedulerException e) {
544 logger.error(e.getMessage(),e);
552 * Pause all triggers - similar to calling <code>pauseTriggerGroup(group)</code>
553 * on every group, however, after using this method <code>resumeAll()</code>
554 * must be called to clear the scheduler's state of 'remembering' that all
555 * new triggers will be paused as they are added.
558 public static Boolean pauseAll(){
563 } catch (SchedulerException e) {
564 logger.error(e.getMessage(),e);
571 * Resume (un-pause) all triggers - similar to calling
572 * <code>resumeTriggerGroup(group)</code> on every group.
575 * If any <code>Trigger</code> missed one or more fire-times, then the
576 * <code>Trigger</code>'s misfire instruction will be applied.
580 public static Boolean resumeAll(){
585 } catch (SchedulerException e) {
586 logger.error(e.getMessage(),e);
593 * run a job with specified trigger
598 public static Date runJob(JobDetail job,Trigger trigger){
600 if(job!=null && trigger!=null){
602 date = schedulerAJobWithTrigger(job,trigger);
607 // public static Trigger getTrigger(String getNewestTriggerName){}