Implementation of Springboot timed tasks

Source: Internet
Author: User

This paper introduces two kinds of implementation methods, and configures implementation and read database timer task configuration implementation.

The configuration implementation is relatively straightforward. Direct code:

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

@ComponentScan
@EnableTransactionManagement (Proxytargetclass = True) br/> @MapperScan ({"Com.*.model.*.mapper", "Com.*.task"})

public class Startapplication {

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

}br/> Note: Add annotations on the startup class
@EnableScheduling

No other place to pay attention.

Timed Task Configuration class:
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()));}

}

The configuration is complete, and the scheduled tasks that are configured after the project is started are automatically executed.

Springboot the database implementation method of the timed task:
Data table Entity
ID, execution class, execution method, whether effective, time expression;

Springboot Timing Task Implementation principle: Start spring will scan the @scheduled annotations and read the annotation configuration information.
Get timed tasks, parse, and register as an executable scheduled task.

Database Activity Timing Task implementation specific code is as follows
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;
/***

  • The timer task starts the class and reads the scheduled task configuration from the database. Monitor timed task runs.
  • @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 ());
    Task Scheduler Object reference
    Private Object Scheduler;

    Private String Beanname;

    Private Beanfactory beanfactory;
    Configuring Environment Context Information
    Private ApplicationContext ApplicationContext;
    Task scheduling registry, monitoring scheduled tasks, set up a timed task start trigger.
    Private final Scheduledtaskregistrar registrar = new Scheduledtaskregistrar ();

    Timed Task Execution Body
    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
    < p="">

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

    }

    /**

    • Timed Task Registration
      */
      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) {
      Log records
      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) {
      Log records
      Ex3.printstacktrace ();
      }
      }
      catch (Nosuchbeandefinitionexception ex2) {
      Exception Log
      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);
      }
      }

    /**

    • Timed Task Assembly
    • @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 = 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 taskssynchronized (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) {
      Log
      Ex.printstacktrace ();
      }
      }
      /**

    • Get Environment Context Information br/>*/
      @Override

      This.applicationcontext = ApplicationContext;
      if (this.beanfactory = = null) {
      This.beanfactory = ApplicationContext;
      }
      }
      }

Implementation of Springboot timed tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.