SpringBoot基于数据库实现定时任务过程解析

网友投稿 374 2022-12-17


SpringBoot基于数据库实现定时任务过程解析

这篇文章主要介绍了SpringBoot基于数据库实现定时任务过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

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

@Configuration

@EnableScheduling

public class SimpleScheduleTask {

//10秒钟执行一次

@Scheduled(cron = "0/10 * * * * ?")

private void tasks() {

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

public 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 tasks = getAllScheduleTasks();

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("task start error:" + tasks.get(i).getClassName() + ";" + tasks.get(i).getMethodName() + ";" + e.getMessage());

}

}

}

logger.info("started task number="+count+"; time="+sdf.format(new Date()));

};

/**

* 获取要执行的所有任务

* @return

*/

private List 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;

}

};

}

/**

* 校验数据

*

* @param list

* @return

*/

private List checkDataList(List list) {

String msg="";

for(int i=0;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);

}

return list;

}

/**

* 按每一条校验数据

*

* @parahttp://m 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;

}

}

数据库配置

运行的结果

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

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

}

return list;

}

/**

* 按每一条校验数据

*

* @parahttp://m 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;

}

}

数据库配置

运行的结果

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java你告诉我 fail
下一篇:Java日期时间及日期相互转换实现代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~