溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中怎么利用數(shù)據(jù)庫實現(xiàn)一個定時任務(wù)

發(fā)布時間:2021-08-07 11:41:14 來源:億速云 閱讀:143 作者:Leah 欄目:編程語言

SpringBoot中怎么利用數(shù)據(jù)庫實現(xiàn)一個定時任務(wù),很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

基于注解來創(chuàng)建定時任務(wù)非常簡單,只需幾行代碼便可完成。實現(xiàn)如下:

@Configuration@EnableSchedulingpublic class SimpleScheduleTask {   //10秒鐘執(zhí)行一次  @Scheduled(cron = "0/10 * * * * ?")  private void tasks() {    System.out.println("【定時任務(wù)】 每10秒執(zhí)行一次!");  }}

Cron表達式參數(shù)分別表示(從左到右):秒(0~59) 如0/5表示每5秒分(0~59)時(0~23)日(0~31) 月的某一天月(0~11)周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

就上面幾行代碼,就能搞定一個定時任務(wù)。顯然,使用Scheduled 確實特別的方便,但有很大的缺點和局限,就是當(dāng)我們調(diào)整了執(zhí)行計劃的時間時,需要重啟服務(wù)才能生效,這就有些不方便。為了達到實時生效的效果,可以通過數(shù)據(jù)庫來動態(tài)實現(xiàn)定時任務(wù)。

基于數(shù)據(jù)庫的動態(tài)定時任務(wù)實現(xiàn)

將定時任務(wù)配置在數(shù)據(jù)庫,啟動項目的時候,用mybatis讀取數(shù)據(jù)庫,實例化對象,并設(shè)定定時任務(wù)。如果需要新增,減少,修改定時任務(wù),僅需要修改數(shù)據(jù)庫資料,并重啟項目即可,無需改代碼。

@Lazy(value = false)@Componentpublic class ScheduleTask implements SchedulingConfigurer {   protected static Logger logger = LoggerFactory.getLogger(ScheduleTask.class);  private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   @Autowired  private ScheduleTaskMapper scheduleTaskMapper;   @Override  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {    List<ScheduleTask> tasks = getAllScheduleTasks();    logger.info("【定時任務(wù)啟動】 啟動任務(wù)數(shù):"+tasks.size()+"; time="+sdf.format(new Date()));     //校驗數(shù)據(jù)    checkDataList(tasks);    //通過校驗的數(shù)據(jù)執(zhí)行定時任務(wù)    int count = 0;    if(tasks.size()>0) {      for (int i = 0; i < tasks.size(); i++) {        try {          taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)), getTrigger(tasks.get(i)));          count++;        } catch (Exception e) {          logger.error("task start error:" + tasks.get(i).getClassName() + ";" + tasks.get(i).getMethodName() + ";" + e.getMessage());        }      }    }    logger.info("started task number="+count+"; time="+sdf.format(new Date()));  };  /** * 獲取要執(zhí)行的所有任務(wù) * @return */  private List<ScheduleTask> getAllScheduleTasks() {    ScheduleTaskExample example=new ScheduleTaskExample();    example.createCriteria().andIsDeleteEqualTo((byte) 0);    return scheduleTaskMapper.selectByExample(example);  }   /** * 獲取Runnable * * @param task * @return */  private Runnable getRunnable(ScheduleTask task){    return new Runnable() {      @Override      public void run() {        try {          Object obj = SpringUtil.getBean(task.getClassName());          Method method = obj.getClass().getMethod(task.getMethodName(),null);          method.invoke(obj);        } catch (InvocationTargetException e) {          logger.error("refect exception:"+task.getClassName()+";"+task.getMethodName()+";"+ e.getMessage());        } catch (Exception e) {          logger.error(e.getMessage());        }      }    };  }  /** * 獲取Trigger * * @param task * @return */  private Trigger getTrigger(ScheduleTask task){    return new Trigger() {      @Override      public Date nextExecutionTime(TriggerContext triggerContext) {        //將Cron 0/1 * * * * ?        CronTrigger trigger = new CronTrigger(task.getCron());        Date nextExec = trigger.nextExecutionTime(triggerContext);        return nextExec;      }    };  }   /** * 校驗數(shù)據(jù) * * @param list * @return */  private List<ScheduleTask> checkDataList(List<ScheduleTask> list) {    String msg="";    for(int i=0;i<list.size();i++){      if(!checkOneData(list.get(i)).equalsIgnoreCase("ok")){        msg+=list.get(i).getTaskName()+";";        list.remove(list.get(i));        i--;      };    }    if(!StringUtils.IsEmpty(msg)){      msg="未啟動的任務(wù):"+msg;      logger.error(msg);    }    return list;  }  /** * 按每一條校驗數(shù)據(jù) * * @param task * @return */  private String checkOneData(ScheduleTask task){    String result="ok";    Class cal= null;    try {      cal = Class.forName(task.getClassName());      Object obj =SpringUtil.getBean(cal);      Method method = obj.getClass().getMethod(task.getMethodName(),null);      String cron=task.getCron();      if(StringUtils.isBlank(cron)){        result="no found the cron:"+task.getTaskName();        logger.error(result);      }    } catch (ClassNotFoundException e) {      result="not found the class:"+task.getClassName()+ e.getMessage();      logger.error(result);    } catch (NoSuchMethodException e) {      result="not found the method:"+task.getClassName()+";"+task.getMethodName()+";"+ e.getMessage();      logger.error(result);    } catch (Exception e) {     logger.error(e.getMessage());     }    return result;  }}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI