SpringBoot實現資料庫配置定時任務
阿新 • • 發佈:2018-11-03
spring-boot 2.0.2.RELEASE,將定時任務配置在資料庫,啟動專案的時候,用mybatis讀取資料庫,例項化物件,並設定定時任務。如果需要新增,減少,修改定時任務,僅需要修改資料庫資料,並重啟專案即可,無需改程式碼。
完整原始碼下載 https://download.csdn.net/download/howard789/10567928
package com.example.scheduledTask; import com.example.mybatis.dao.SysTaskMapper; import com.example.mybatis.model.SysTask; import com.example.mybatis.model.SysTaskExample; import com.example.util.SpringUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Lazy(value = false) @Component public class SysTaskConfig implements SchedulingConfigurer { protected static Logger logger = LoggerFactory.getLogger(SysTaskConfig.class); private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Resource private SysTaskMapper sysTaskMapper; //從資料庫裡取得所有要執行的定時任務 private List<SysTask> getAllTasks() { SysTaskExample example=new SysTaskExample(); example.createCriteria().andIsDeleteEqualTo((byte) 0); return sysTaskMapper.selectByExample(example); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { List<SysTask> tasks=getAllTasks(); logger.info("定時任務啟動,預計啟動任務數量="+tasks.size()+"; time="+sdf.format(new Date())); //校驗資料(這個步驟主要是為了列印日誌,可以省略) checkDataList(tasks); //通過校驗的資料執行定時任務 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("定時任務啟動錯誤:" + tasks.get(i).getClassName() + ";" + tasks.get(i).getMethodName() + ";" + e.getMessage()); } } } logger.info("定時任務實際啟動數量="+count+"; time="+sdf.format(new Date())); }; private Runnable getRunnable(SysTask 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("定時任務啟動錯誤,反射異常:"+task.getClassName()+";"+task.getMethodName()+";"+ e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } } }; } private Trigger getTrigger(SysTask 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; } }; } private List<SysTask> checkDataList(List<SysTask> list) { String errMsg=""; for(int i=0;i<list.size();i++){ if(!checkOneData(list.get(i)).equalsIgnoreCase("success")){ errMsg+=list.get(i).getTaskName()+";"; list.remove(list.get(i)); i--; }; } if(!StringUtils.isBlank(errMsg)){ errMsg="未啟動的任務:"+errMsg; logger.error(errMsg); } return list; } private String checkOneData(SysTask task){ String result="success"; 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="定時任務啟動錯誤,無cron:"+task.getTaskName(); logger.error(result); } } catch (ClassNotFoundException e) { result="定時任務啟動錯誤,找不到類:"+task.getClassName()+ e.getMessage(); logger.error(result); } catch (NoSuchMethodException e) { result="定時任務啟動錯誤,找不到方法,方法必須是public:"+task.getClassName()+";"+task.getMethodName()+";"+ e.getMessage(); logger.error(result); } catch (Exception e) { logger.error(e.getMessage()); } return result; } }
資料庫配置
執行的結果