• Quartz学习笔记2(封装)


    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;

    2

    3 import org.apache.commons.lang.StringUtils;

    4 import org.quartz.*;

    5 import org.quartz.impl.StdSchedulerFactory;

    6 import org.quartz.impl.matchers.GroupMatcher;

    7 import org.slf4j.Logger;

    8 import org.slf4j.LoggerFactory;

    9

    10 import java.util.*;

    11

    12 /**

    13 * User: luowei

    14 * Date: 12-7-9

    15 * Time: 上午10:00

    16 */

    17 public class JobUtil {

    18 protected static Logger logger = (Logger) LoggerFactory.getLogger(JobUtil.class);

    19

    20 /**

    21 * define a scheduler ,will be a sington instance

    22 */

    23 private static Scheduler scheduler = null;

    24

    25 /**

    26 * get the name with default name 'QuartzScheduler' scheduler

    27 * @return

    28 */

    29 public static Scheduler getScheduler(){

    30 if(scheduler == null){

    31 SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    32 try {

    33 scheduler = schedulerFactory.getScheduler();

    34 } catch (SchedulerException e) {

    35 logger.error(e.getMessage(),e);

    36 }

    37 }

    38 return scheduler;

    39 }

    40

    41 /**

    42 * get the scheduler with named shcedulerName

    43 * @param schedulerName

    44 * @return

    45 */

    46 public static Scheduler getScheduler(String schedulerName){

    47 if(scheduler == null){

    48 SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    49 try {

    50 scheduler = schedulerFactory.getScheduler(schedulerName);

    51 } catch (SchedulerException e) {

    52 logger.error(e.getMessage(),e);

    53 }

    54 }

    55 return scheduler;

    56 }

    57

    58 /**

    59 * scheduler a job with specefied trigger

    60 * @param job

    61 * @param trigger

    62 * @return

    63 */

    64 public static Date schedulerAJobWithTrigger(JobDetail job,Trigger trigger){

    65 Date date = null;

    66 if(scheduler == null){

    67 scheduler = getScheduler();

    68 }

    69 try {

    70 if(!scheduler.checkExists(job.getKey())

    71 && !scheduler.checkExists(trigger.getKey())){

    72 date = scheduler.scheduleJob(job,trigger);

    73 }

    74 } catch (SchedulerException e) {

    75 logger.error(e.getMessage(),e);

    76 }

    77 return date;

    78 }

    79

    80 /**

    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.

    85 *

    86 * @param triggerKey identity of the trigger to replace

    87 * @param newTrigger

    88 * The new <code>Trigger</code> to be stored.

    89 *

    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.

    94 */

    95 public static Date reSchedulerJob(TriggerKey triggerKey,Trigger newTrigger){

    96 Date date = null;

    97 try {

    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);

    103 }

    104 return date;

    105 }

    106

    107 /**

    108 * scheduler a job with specefied trigger in a specefied shceduler

    109 * @param schedulerName

    110 * @param job

    111 * @param trigger

    112 * @return

    113 */

    114 public static Date schedulerAJobWithTrigger(String schedulerName,JobDetail job,Trigger trigger){

    115 Date date = null;

    116 if(scheduler == null){

    117 scheduler = getScheduler(schedulerName);

    118 }

    119 try {

    120 if(!scheduler.checkExists(job.getKey())

    121 && scheduler.checkExists(trigger.getKey())){

    122 date = scheduler.scheduleJob(job,trigger);

    123 }

    124 } catch (SchedulerException e) {

    125 logger.error(e.getMessage(),e);

    126 }

    127 return date;

    128 }

    129

    130 /**

    131 * start scheduler

    132 * @return

    133 */

    134 public static Boolean startScheduler(){

    135 Boolean flag = false;

    136 try {

    137 if(scheduler == null){

    138 scheduler = getScheduler();

    139 }

    140 if(!scheduler.isStarted()){

    141 scheduler.start();

    142 }

    143 flag = true;

    144 return flag;

    145 } catch (SchedulerException e) {

    146 logger.error(e.getMessage(),e);

    147 return flag;

    148 }

    149 }

    150

    151 /**

    152 * shutdown scheduler

    153 * @return

    154 */

    155 public static Boolean shutdownScheduler(){

    156 try {

    157 if(scheduler != null && !scheduler.isShutdown()){

    158 scheduler.shutdown();

    159 }

    160 return true;

    161 } catch (SchedulerException e) {

    162 logger.error(e.getMessage(),e);

    163 return false;

    164 }

    165 }

    166

    167 /**

    168 * trigger key list

    169 */

    170 public static Map<String,TriggerKey> triggerKeyMap = new HashMap<String,TriggerKey>();

    171

    172 /**

    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

    179 */

    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))

    188 .build();

    189 triggerKeyMap.put(triggerName, trigger.getKey());

    190 }

    191 return trigger;

    192 }

    193

    194 /**

    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

    201 */

    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)

    209 .startAt(startTime)

    210 .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(intervalInMinutes))

    211 .build();

    212 triggerKeyMap.put(triggerName, trigger.getKey());

    213 }

    214 return trigger;

    215 }

    216

    217 /**

    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

    223 * @return a SimpleTrigger

    224 */

    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)

    232 .startAt(startTime)

    233 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(intervalInSeconds))

    234 .build();

    235 }

    236 triggerKeyMap.put(triggerName, trigger.getKey());

    237 return trigger;

    238 }

    239

    240 /**

    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

    246 * @param count count

    247 * @param seconds seconds

    248 * @return a SimpleTrigger

    249 */

    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)

    257 .startAt(startTime)

    258 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(count,seconds))

    259 .build();

    260 triggerKeyMap.put(triggerName, trigger.getKey());

    261 }

    262 return trigger;

    263 }

    264

    265 /**

    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).

    269 * @param groupName

    270 * @param triggerName

    271 * @param startTime

    272 * @param cronExpression

    273 * @return a CronTrigger

    274 */

    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)

    282 .startAt(startTime)

    283 .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))

    284 .build();

    285 triggerKeyMap.put(triggerName, trigger.getKey());

    286 }

    287 return trigger;

    288 }

    289

    290 public static Map<String,JobKey> jobKeyMap = new HashMap<String,JobKey>();

    291

    292 /**

    293 * init a job with the specified jobName,groupName and clazz

    294 *

    295 * @param groupName

    296 * @param jobName

    297 * @param clazz

    298 * @return

    299 */

    300 public static JobDetail initJob(String groupName, String jobName, Class<? extends Job> clazz){

    301 JobDetail job = null;

    302 if(StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(groupName) && clazz!=null){

    303 job = JobBuilder.newJob((Class<? extends Job>) clazz)

    304 .withIdentity(jobName,groupName)

    305 .build();

    306 jobKeyMap.put(jobName, job.getKey());

    307 }

    308 return job;

    309 }

    310

    311 /**

    312 * init durable job

    313 * @param groupName

    314 * @param jobName

    315 * @param clazz

    316 * @return

    317 */

    318 public static JobDetail initDurableJob(String groupName, String jobName, Class<? extends Job> clazz){

    319 JobDetail job = null;

    320 if(StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(groupName) && clazz!=null){

    321 job = JobBuilder.newJob((Class<? extends Job>) clazz)

    322 .withIdentity(jobName,groupName)

    323 .storeDurably()

    324 .build();

    325 jobKeyMap.put(jobName, job.getKey());

    326 }

    327 return job;

    328 }

    329

    330 /**

    331 * add data to JobDetail,which data were stored in map

    332 * @param jobDetail jobDetail

    333 * @param map map

    334 * @return

    335 */

    336 public static Boolean setData2Job(JobDetail jobDetail,Map<? extends String,? extends Object> map){

    337 if(jobDetail!=null && map!=null){

    338 jobDetail.getJobDataMap().putAll(map);

    339 return true;

    340 }else{

    341 return false;

    342 }

    343 }

    344

    345 /**

    346 * add data to Trigger,which data were stored in map

    347 * @param trigger trigger

    348 * @param map map

    349 * @return

    350 */

    351 public static Boolean setData2Trigger(Trigger trigger,Map<? extends String,? extends Object> map) {

    352 if(trigger!=null && map!=null){

    353 trigger.getJobDataMap().putAll(map);

    354 return true;

    355 }else {

    356 return false;

    357 }

    358 }

    359

    360 /**

    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

    363 * @param jobName

    364 * @return

    365 */

    366 public static Boolean delJob(String jobName){

    367 Boolean flag = false;

    368 if(StringUtils.isNotBlank(jobName)){

    369 JobKey jobKey = jobKeyMap.get(jobName);

    370 try {

    371 scheduler.deleteJob(jobKey);

    372 jobKeyMap.remove(jobName);

    373 flag = true;

    374 } catch (SchedulerException e) {

    375 logger.error(e.getMessage(),e);

    376 flag = false;

    377 }

    378 }

    379 return flag;

    380 }

    381

    382 /**

    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

    385 * @return

    386 */

    387 public static Boolean delAllJob(){

    388 Boolean flag = false;

    389 try {

    390 List<JobKey> jobKeyList = new ArrayList<JobKey>();

    391 jobKeyList.addAll(jobKeyMap.values());

    392 scheduler.deleteJobs(jobKeyList);

    393 jobKeyMap.clear();

    394 flag = true;

    395 } catch (SchedulerException e) {

    396 logger.error(e.getMessage(),e);

    397 flag = false;

    398 }

    399 return flag;

    400 }

    401

    402 /**

    403 * Resume (un-pause) the <code>{@link org.quartz.JobDetail}</code> with

    404 * the given key.

    405 *

    406 * <p>

    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.

    410 * </p>

    411 * @param jobName

    412 * @return

    413 */

    414 public static Boolean pauseJob(String jobName){

    415 Boolean flag = false;

    416 if(StringUtils.isNotBlank(jobName)){

    417 JobKey jobKey = jobKeyMap.get(jobName);

    418 try {

    419 scheduler.pauseJob(jobKey);

    420 flag = true;

    421 } catch (SchedulerException e) {

    422 logger.error(e.getMessage(),e);

    423 flag = false;

    424 }

    425 }

    426 return flag;

    427 }

    428

    429 /**

    430 * Resume (un-pause) the <code>{@link org.quartz.JobDetail}</code> with

    431 * the given key.

    432 *

    433 * <p>

    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.

    437 * </p>

    438 *

    439 * @param jobName jobName

    440 * @return

    441 */

    442 public static Boolean resumeJob(String jobName){

    443 Boolean flag = false;

    444 if(StringUtils.isNotBlank(jobName)){

    445 JobKey jobKey = jobKeyMap.get(jobName);

    446 try {

    447 scheduler.resumeJob(jobKey);

    448 flag = true;

    449 } catch (SchedulerException e) {

    450 logger.error(e.getMessage(),e);

    451 flag = false;

    452 }

    453 }

    454 return flag;

    455 }

    456

    457 /**

    458 * Remove the indicated <code>{@link Trigger}</code> from the scheduler.

    459 *

    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>

    462 */

    463 public static Boolean unscheduleJob(String triggerName){

    464 Boolean flag = false;

    465 if(StringUtils.isNotBlank(triggerName)){

    466 TriggerKey triggerKey = triggerKeyMap.get(triggerName);

    467 try {

    468 scheduler.unscheduleJob(triggerKey);

    469 flag = true;

    470 } catch (SchedulerException e) {

    471 logger.error(e.getMessage(),e);

    472 flag = false;

    473 }

    474 }

    475 return flag;

    476 }

    477

    478 /**

    479 * Remove all of the indicated <code>{@link Trigger}</code>s from the scheduler.

    480 *

    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>

    483 *

    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

    488 * of time).</p>

    489 */

    490 public static Boolean unscheduleJobs(){

    491 Boolean flag = false;

    492 try {

    493 List<TriggerKey> triggerKeyList = new ArrayList<TriggerKey>();

    494 triggerKeyList.addAll(triggerKeyMap.values());

    495 scheduler.unscheduleJobs(triggerKeyList);

    496 flag = true;

    497 } catch (SchedulerException e) {

    498 logger.error(e.getMessage(),e);

    499 flag = false;

    500 }

    501 return flag;

    502 }

    503

    504 /**

    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

    507 * @param triggerName

    508 * @return

    509 */

    510 public static Boolean pauseTrigger(String triggerName){

    511 Boolean flag = false;

    512 if(StringUtils.isNotBlank(triggerName)){

    513 TriggerKey triggerKey = triggerKeyMap.get(triggerName);

    514 try {

    515 scheduler.pauseTrigger(triggerKey);

    516 flag = true;

    517 } catch (SchedulerException e) {

    518 logger.error(e.getMessage(),e);

    519 flag = false;

    520 }

    521 }

    522 return flag;

    523 }

    524

    525 /**

    526 * Resume (un-pause) the <code>{@link Trigger}</code> with the given

    527 * key.

    528 *

    529 * <p>

    530 * If the <code>Trigger</code> missed one or more fire-times, then the

    531 * <code>Trigger</code>'s misfire instruction will be applied.

    532 * </p>

    533 * @param triggerName

    534 * @return

    535 */

    536 public static Boolean resumeTrigger(String triggerName){

    537 Boolean flag = false;

    538 if(StringUtils.isNotBlank(triggerName)){

    539 TriggerKey triggerKey = triggerKeyMap.get(triggerName);

    540 try {

    541 scheduler.resumeTrigger(triggerKey);

    542 flag = true;

    543 } catch (SchedulerException e) {

    544 logger.error(e.getMessage(),e);

    545 flag = false;

    546 }

    547 }

    548 return flag;

    549 }

    550

    551 /**

    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.

    556 * @return

    557 */

    558 public static Boolean pauseAll(){

    559 Boolean flag = false;

    560 try {

    561 scheduler.pauseAll();

    562 flag = true;

    563 } catch (SchedulerException e) {

    564 logger.error(e.getMessage(),e);

    565 flag = false;

    566 }

    567 return flag;

    568 }

    569

    570 /**

    571 * Resume (un-pause) all triggers - similar to calling

    572 * <code>resumeTriggerGroup(group)</code> on every group.

    573 *

    574 * <p>

    575 * If any <code>Trigger</code> missed one or more fire-times, then the

    576 * <code>Trigger</code>'s misfire instruction will be applied.

    577 * </p>

    578 * @return

    579 */

    580 public static Boolean resumeAll(){

    581 Boolean flag = false;

    582 try {

    583 scheduler.resumeAll();

    584 flag = true;

    585 } catch (SchedulerException e) {

    586 logger.error(e.getMessage(),e);

    587 flag = false;

    588 }

    589 return flag;

    590 }

    591

    592 /**

    593 * run a job with specified trigger

    594 * @param job job

    595 * @param trigger trigger

    596 * @return

    597 */

    598 public static Date runJob(JobDetail job,Trigger trigger){

    599 Date date = null;

    600 if(job!=null && trigger!=null){

    601 startScheduler();

    602 date = schedulerAJobWithTrigger(job,trigger);

    603 }

    604 return date;

    605 }

    606

    607 // public static Trigger getTrigger(String getNewestTriggerName){}

    608

    609 }

    610

  • 相关阅读:
    leetcode-22 括号生成
    Mysql安装与使用(详细)
    java开发环境的搭建
    LeetCode 55. Jump Game
    LeetCode 31. Next Permutation
    2019.1.12国家开发银行(国开行)笔试【补录】+ 面试总结
    苹果电脑MAMP环境配置以及关于“星球大战”知识图谱的复现
    创新工场-Deecamp2019冬令营笔试A卷 AND 面试内容
    使用scp命令在mac本机和linux服务器之间传输数据
    python小技巧之多行缩进,获取程序运行时间,删除非空文件夹
  • 原文地址:https://www.cnblogs.com/luowei010101/p/2592377.html
Copyright © 2020-2023  润新知