SpringBoot基于数据库如何实现定时任务

这篇文章主要介绍了SpringBoot基于数据库如何实现定时任务,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

在我们平时开发的项目中,定时任务基本属于必不可少的功能,那大家都是怎么做的呢?但我知道的大多都是静态定时任务实现。

基于注解来创建定时任务非常简单,只需几行代码便可完成。实现如下:

@Configuration
@EnableScheduling
publicclassSimpleScheduleTask{

//10秒钟执行一次
@Scheduled(cron="0/10****?")
privatevoidtasks(){
System.out.println("【定时任务】每10秒执行一次!");
}
}

Cron表达式参数分别表示(从左到右):秒(0~59) 如0/5表示每5秒分(0~59)时(0~23)日(0~31) 月的某一天月(0~11)周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

就上面几行代码,就能搞定一个定时任务。显然,使用Scheduled 确实特别的方便,但有很大的缺点和局限,就是当我们调整了执行计划的时间时,需要重启服务才能生效,这就有些不方便。为了达到实时生效的效果,可以通过数据库来动态实现定时任务。

基于数据库的动态定时任务实现

将定时任务配置在数据库,启动项目的时候,用mybatis读取数据库,实例化对象,并设定定时任务。如果需要新增,减少,修改定时任务,仅需要修改数据库资料,并重启项目即可,无需改代码。

@Lazy(value=false)
@Component
publicclassScheduleTaskimplementsSchedulingConfigurer{

protectedstaticLoggerlogger=LoggerFactory.getLogger(ScheduleTask.class);
privateSimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");

@Autowired
privateScheduleTaskMapperscheduleTaskMapper;

@Override
publicvoidconfigureTasks(ScheduledTaskRegistrartaskRegistrar){
List<ScheduleTask>tasks=getAllScheduleTasks();
logger.info("【定时任务启动】启动任务数:"+tasks.size()+";time="+sdf.format(newDate()));

//校验数据
checkDataList(tasks);
//通过校验的数据执行定时任务
intcount=0;
if(tasks.size()>0){
for(inti=0;i<tasks.size();i++){
try{
taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)),getTrigger(tasks.get(i)));
count++;
}catch(Exceptione){
logger.error("taskstarterror:"+tasks.get(i).getClassName()+";"+tasks.get(i).getMethodName()+";"+e.getMessage());
}
}
}
logger.info("startedtasknumber="+count+";time="+sdf.format(newDate()));
};

/**
*获取要执行的所有任务
*@return
*/
privateList<ScheduleTask>getAllScheduleTasks(){
ScheduleTaskExampleexample=newScheduleTaskExample();
example.createCriteria().andIsDeleteEqualTo((byte)0);
returnscheduleTaskMapper.selectByExample(example);
}

/**
*获取Runnable
*
*@paramtask
*@return
*/
privateRunnablegetRunnable(ScheduleTasktask){
returnnewRunnable(){
@Override
publicvoidrun(){
try{
Objectobj=SpringUtil.getBean(task.getClassName());
Methodmethod=obj.getClass().getMethod(task.getMethodName(),null);
method.invoke(obj);
}catch(InvocationTargetExceptione){
logger.error("refectexception:"+task.getClassName()+";"+task.getMethodName()+";"+e.getMessage());
}catch(Exceptione){
logger.error(e.getMessage());
}
}
};
}

/**
*获取Trigger
*
*@paramtask
*@return
*/
privateTriggergetTrigger(ScheduleTasktask){
returnnewTrigger(){
@Override
publicDatenextExecutionTime(TriggerContexttriggerContext){
//将Cron0/1****?
CronTriggertrigger=newCronTrigger(task.getCron());
DatenextExec=trigger.nextExecutionTime(triggerContext);
returnnextExec;
}
};
}

/**
*校验数据
*
*@paramlist
*@return
*/
privateList<ScheduleTask>checkDataList(List<ScheduleTask>list){
Stringmsg="";
for(inti=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="未启动的任务:"+msg;
logger.error(msg);
}
returnlist;
}

/**
*按每一条校验数据
*
*@paramtask
*@return
*/
privateStringcheckOneData(ScheduleTasktask){
Stringresult="ok";
Classcal=null;
try{
cal=Class.forName(task.getClassName());
Objectobj=SpringUtil.getBean(cal);
Methodmethod=obj.getClass().getMethod(task.getMethodName(),null);
Stringcron=task.getCron();
if(StringUtils.isBlank(cron)){
result="nofoundthecron:"+task.getTaskName();
logger.error(result);
}
}catch(ClassNotFoundExceptione){
result="notfoundtheclass:"+task.getClassName()+e.getMessage();
logger.error(result);
}catch(NoSuchMethodExceptione){
result="notfoundthemethod:"+task.getClassName()+";"+task.getMethodName()+";"+e.getMessage();
logger.error(result);
}catch(Exceptione){
logger.error(e.getMessage());
}
returnresult;
}
}

数据库配置

SpringBoot基于数据库如何实现定时任务

运行的结果

SpringBoot基于数据库如何实现定时任务

这样我们可以通过直接修改数据库,执行周期就会改变,并且不需要我们重启应用,十分方便。

感谢你能够认真阅读完这篇文章,希望小编分享的“SpringBoot基于数据库如何实现定时任务”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!

发布于 2021-05-30 14:09:10
收藏
分享
海报
0 条评论
157
上一篇:H5 canvas中width、height和style的宽高区别分析 下一篇:python中scrapy重复执行的实现方法
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码