介绍两种实现方式;配置实现和读取数据库定时任务配置实现。

配置实现比较简单。直接撸代码:

package com;

import java.util.Properties;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplicationbr/>@ImportResource("classpath:/config.xml")
@EnableAutoConfiguration
@ComponentScan
@EnableTransactionManagement(proxyTargetClass = true) br/>@MapperScan({"com.*.model.*.mapper","com.*.task"})
@EnableScheduling
public class StartApplication {

public static void main(String[] args) {SpringApplication.run(StartApplication.class, args);
}@Bean
public DatabaseIdProvider getDatabaseIdProvider() {}

}br/>注:在启动类上加注解
@EnableScheduling
@MapperScan 扫描定时任务配置文件的位置。
其他地方无需关注。

定时任务配置类:
package com.*.task;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class RunTaskConfig {

private static final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
//初始延迟1秒,每隔2秒
@Scheduled(fixedRateString = "2000",initialDelay = 1000)
public void testFixedRate(){System.out.println("fixedRateString,当前时间:" +format.format(new Date()));
}//每次执行完延迟2秒
@Scheduled(fixedDelayString= "2000")
public void testFixedDelay(){System.out.println("fixedDelayString,当前时间:" +format.format(new Date()));
}
//每隔3秒执行一次
@Scheduled(cron="0/3 * * * * ?")
public void testCron(){System.out.println("cron,当前时间:" +format.format(new Date()));
}

}

配置完成,项目启动后配置的定时任务会自动执行。

Springboot 定时任务 的数据库实现方式:
数据表实体
id , 执行类, 执行方法, 是否生效, 时间表达式;

SpringBoot 定时任务实现原理:启动Spring 会扫描@Scheduled 注解,读取注解配置信息。
获取定时任务,解析,注册成可执行的定时任务。

数据库活动定时任务实现具体代码如下
package com.tansun.task;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.NamedBeanHolder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.tansun.model.system.dao.RunTaskDao;
import com.tansun.model.system.dao.RunTaskDaoImpl;
import com.tansun.model.system.dao.RunTaskSqlBulider;
import com.tansun.model.system.entity.RunTask;
import com.tansun.web.framework.util.BeanUtil;
/***

  • 定时任务启动类,从数据库读取定时任务配置。监控定时任务运行。
  • @author kangx
    */
    @Component("BeanDefineConfigue")
    public class EventListen implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware{

    public static final String DEFAULT_TASK_SCHEDULER_BEAN_NAME = "taskScheduler";

    protected final Log logger = LogFactory.getLog(getClass());
    // 任务调度对象引用
    private Object scheduler;

    private String beanName;

    private BeanFactory beanFactory;
    // 配置环境上下文信息
    private ApplicationContext applicationContext;
    // 任务调度注册中心,监控定时任务,设置定时任务启动触发器。
    private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();

    // 定时任务执行体
    private final Map<Object, Set<ScheduledTask>> scheduledTasks =
    new IdentityHashMap<Object, Set<ScheduledTask>>(16);

    public Object getScheduler() {
    return scheduler;
    }

    public void setScheduler(Object scheduler) {
    this.scheduler = scheduler;
    }
    //EmbeddedValueResolver embeddedValueResolver=new EmbeddedValueResolver(null);br/>@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

    try {RunTaskDao runTaskDao = BeanUtil.getBean(RunTaskDaoImpl.class);RunTaskSqlBulider runTaskSqlBulider = new RunTaskSqlBulider();//查找启动状态的定时任务runTaskSqlBulider.andIsWorkEqualTo("1");int count = runTaskDao.countBySqlBulider(runTaskSqlBulider);List<RunTask> list = new ArrayList<>(); if(count>0){list = runTaskDao.selectListBySqlBulider(runTaskSqlBulider);}for(RunTask runtask:list){//定时任务对象解析,装配及注册processScheduled(runtask);}// 定时任务注册,启动定时任务finishRegistration();            } catch (Exception e) {e.printStackTrace();
    }

    }

    /**

    • 定时任务注册
      */
      private void finishRegistration() {
      if (this.scheduler != null) {
      this.registrar.setScheduler(this.scheduler);
      }
      if (this.beanFactory instanceof ListableBeanFactory) {
      Map<String, SchedulingConfigurer> configurers =
      ((ListableBeanFactory) this.beanFactory).getBeansOfType(SchedulingConfigurer.class);
      for (SchedulingConfigurer configurer : configurers.values()) {
      configurer.configureTasks(this.registrar);
      }
      }
      if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
      try {
      this.registrar.setTaskScheduler(resolveSchedulerBean(TaskScheduler.class, false));
      }
      catch (NoUniqueBeanDefinitionException ex) {
      try {
      this.registrar.setTaskScheduler(resolveSchedulerBean(TaskScheduler.class, true));
      }
      catch (NoSuchBeanDefinitionException ex2) {
      // 日志记录
      ex2.printStackTrace();
      }
      }
      catch (NoSuchBeanDefinitionException ex) {
      // Search for ScheduledExecutorService bean next...
      try {
      this.registrar.setScheduler(resolveSchedulerBean(ScheduledExecutorService.class, false));
      }
      catch (NoUniqueBeanDefinitionException ex2) {
      try {
      this.registrar.setScheduler(resolveSchedulerBean(ScheduledExecutorService.class, true));
      }
      catch (NoSuchBeanDefinitionException ex3) {
      // 日志记录
      ex3.printStackTrace();
      }
      }
      catch (NoSuchBeanDefinitionException ex2) {
      // 异常日志
      ex2.printStackTrace();
      }
      }
      }
      this.registrar.afterPropertiesSet();
      }
      private <T> T resolveSchedulerBean(Class<T> schedulerType, boolean byName) {
      if (byName) {
      T scheduler = this.beanFactory.getBean(DEFAULT_TASK_SCHEDULER_BEAN_NAME, schedulerType);
      if (this.beanFactory instanceof ConfigurableBeanFactory) {
      ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(
      DEFAULT_TASK_SCHEDULER_BEAN_NAME, this.beanName);
      }
      return scheduler;
      }
      else if (this.beanFactory instanceof AutowireCapableBeanFactory) {
      NamedBeanHolder<T> holder = ((AutowireCapableBeanFactory) this.beanFactory).resolveNamedBean(schedulerType);
      if (this.beanFactory instanceof ConfigurableBeanFactory) {
      ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(
      holder.getBeanName(), this.beanName);
      }
      return holder.getBeanInstance();
      }
      else {
      return this.beanFactory.getBean(schedulerType);
      }
      }

    /**

    • 定时任务装配
    • @throws ClassNotFoundException
    • @throws SecurityException
    • @throws NoSuchMethodException
      */
      protected void processScheduled(RunTask runTask) throws Exception{
      try {
      Class clazz = Class.forName(runTask.getExecuteClass());
      Object bean = clazz.newInstance();
      Method method = clazz.getMethod(runTask.getExecuteMethod(), null);
      Method invocableMethod = AopUtils.selectInvocableMethod(method, clazz);
      Runnable runnable = new ScheduledMethodRunnable(bean, invocableMethod);
      boolean processedSchedule = false;

      Set<ScheduledTask> tasks = new LinkedHashSet<ScheduledTask>(4);
      String cron = runTask.getTimeExpression();
      if (StringUtils.hasText(cron)) {processedSchedule = true;String zone = "";TimeZone timeZone;if (StringUtils.hasText(zone)) {timeZone = StringUtils.parseTimeZoneString(zone);}else {timeZone = TimeZone.getDefault();}tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
      }
      // Finally register the scheduled tasks
      synchronized (this.scheduledTasks) {Set<ScheduledTask> registeredTasks = this.scheduledTasks.get(bean);if (registeredTasks == null) {registeredTasks = new LinkedHashSet<ScheduledTask>(4);this.scheduledTasks.put(bean, registeredTasks);}registeredTasks.addAll(tasks);
      }

      }
      catch (IllegalArgumentException ex) {
      // 日志
      ex.printStackTrace();
      }
      }
      /**

    • 获取环境上下文信息br/>*/
      @Override
      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
      if (this.beanFactory == null) {
      this.beanFactory = applicationContext;
      }
      }
      }

转载于:https://blog.51cto.com/11232071/2135631

SpringBoot 定时任务的实现相关推荐

  1. SpringBoot定时任务实现的两种方式介绍

    今天给大家介绍SpringBoot定时任务实现的几种方式,希望对大家能有所帮助! 1.SpringTask 用法 框架介绍:SpringTask是Spring自带的轻量级定时任务工具,相比于Quart ...

  2. 开关配置springboot定时任务

    题外话 这是我第五篇原创文章,计划写定时任务内容,想想只要打开自己的有道云笔记,复制粘贴,整理排版一下就能轻松搞定了,这样做有意义吗?自己写文章的价值点是什么呢?考虑了很长时间,主要希望做到一下几点: ...

  3. SpringBoot定时任务(@Scheduled)说明

    转载文章:http://blog.csdn.net/loongshawn/article/details/50663393 1. 定时任务实现方式 定时任务实现方式: Java自带的java.util ...

  4. springBoot 定时任务执行一段时间后失效

    问题描述: springBoot 定时任务执行一段时间后失效,定时任务调用http过一段时间后什么异常也没有 原因:http请求僵死,导致线程也不往下执行,最终导致后面的定时任务也不执行: 解决方法: ...

  5. SpringBoot定时任务简单应用

    SpringBoot定时任务可以用于周期性重复工作的编写,其应用简单,能满足绝大多数需求.在Java中实现定时任务主要有三种实现形式:一是使用JDK 自带的 Timer,二是使用第三方组件 Quart ...

  6. SpringBoot定时任务 - 集成quartz实现定时任务(单实例和分布式两种方式)

    最为常用定时任务框架是Quartz,并且Spring也集成了Quartz的框架,Quartz不仅支持单实例方式还支持分布式方式.本文主要介绍Quartz,基础的Quartz的集成案例本,以及实现基于数 ...

  7. springboot定时任务未登录情况下获取用户信息报错解决方案

    解决org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling ...

  8. SpringBoot定时任务升级篇(动态添加修改删除定时任务)

    (1)思路说明: (a)首先这里我们需要重新认识一个类ThreadPoolTaskScheduler:线程池任务调度类,能够开启线程池进行任务调度. (b)ThreadPoolTaskSchedule ...

  9. Java 实现 Springboot 定时任务(每隔一段时间自动执行一次)

    Java实现非Web项目的Springboot定时任务(每3秒自动执行一次) 前言 一.新建Java Springboot项目 二.示例代码 运行效果 总结 前言 运行非Web的Springboot项 ...

最新文章

  1. XXX管理平台系统——项目教训
  2. 浅谈JavaScript中按键事件的e.keyCode || e.which || e.charCode
  3. 从JVM的常见异常来看Tomcat中内存的设置
  4. Internet导致业务绩效降低的4个怪原因—Vecloud微云
  5. mlx rdma网卡指标参数简介
  6. Webpack 10分钟入门
  7. RecyclerView分割线的技巧
  8. kotlin字符串数组_Kotlin程序读取,遍历,反向和排序字符串数组
  9. SpringBoot入门教程
  10. 内卷、996的背后,AI技术该如何服务企业“人、财、物”?
  11. pythonxml读写_python xml读取和写入
  12. go mysql 条件查询_go-sql-driver包 实现mysql不定字段查询
  13. 设计模式之——bridge模式
  14. java基础学习总结——流
  15. 性能测试--jmeter如何发送get请求【3】
  16. input框背景设置透明
  17. 神奇软件:良心浏览器 纯净无捆绑,还有亿点点好用360极速浏览器X
  18. 2N个数排成一行(每个数有2个), 2个1之间有1个数,2个2 之间有2个数,...2个N之间有N个数... 例312132
  19. 境外上市,一个绝非遥不可及的梦想!
  20. 巨头集体跨界,老玩家悄然出圈,谁在争夺6亿电竞用户?

热门文章

  1. oracle 速度最快 驱动,c# – Oracle ODP.NET托管驱动程序在64位运行速度比在32位运行速度慢50-100%...
  2. 绝对路径${pageContext.request.contextPath}的使用
  3. 关于安装360安全桌面后 iis服务不好使的解决方法
  4. 游戏开发 入职6个月 牢骚型小结
  5. EEG巨型分析I:跨研究的频谱和振幅特征
  6. 2023中国(深圳)国际激光及焊接展览会
  7. 合根植物,小猪存钱罐(python)
  8. cad==sketchup
  9. 在研究所月入两万,是一种什么体验?
  10. 资产配置那些事-常用理财工具2