spring boot的定时任务应该如何使用

发布网友

我来回答

2个回答

懂视网

定时任务1

import lombok.extern.slf4j.Slf4j;

/**
 * @author Created by niugang on 2019/12/24/15:29
 */
@Slf4j
public class TaskTest {


 public void task1() {
 log.info("反射调用测试[一]类");
 }
}

定时任务2

import lombok.extern.slf4j.Slf4j;

/**
 * @author Created by niugang on 2019/12/24/15:54
 */
@Slf4j
public class TaskTest2 {
 public void task2() {
 log.info("反射调用测试[二]类");
 }
}

配置类

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
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 java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Created by niugang on 2019/12/24/15:19
 */
@Configuration
@EnableScheduling
@Slf4j
public class CompleteScheduleConfig implements SchedulingConfigurer {

 private static List<TaskRecord> taskRecordList = new ArrayList<>();


 /*
 *模拟数据库存储
 */
 static {
 TaskRecord taskRecord = new TaskRecord();
 taskRecord.setExecuteMehod("task1");
 taskRecord.setClassPath("com.example.demo.pojo.TaskTest");
 taskRecord.setCron("0/5 * * * * ?");
 taskRecordList.add(taskRecord);

 TaskRecord taskRecord2 = new TaskRecord();
 taskRecord2.setExecuteMehod("task2");
 taskRecord2.setClassPath("com.example.demo.pojo.TaskTest2");
 taskRecord2.setCron("0/10 * * * * ?");
 taskRecordList.add(taskRecord2);
 }


 @Override
 public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
 // taskRegistrar.addCronTask(() -> log.info("执行定时任务,{}", LocalDateTime.now()), "0/5 * * * * ?");
/* taskRegistrar.addCronTask(new Runnable() {
  @Override
  public void run() {
  try {
   Class<?> aClass = Class.forName("com.example.demo.pojo.TaskTest");
   Object o = aClass.newInstance();
   Method[] declaredMethods = aClass.getDeclaredMethods();
   for (Method declaredMethod : declaredMethods) {
   declaredMethod.invoke(o);
   // log.info("方法名称:{}",declaredMethod.getName());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  }
 }, "0/5 * * * * ?");*/

 for (TaskRecord taskRecord : taskRecordList) {
  String classPath = taskRecord.getClassPath();
  String cron = taskRecord.getCron();
  String executeMehod = taskRecord.getExecuteMehod();
  Runnable runnable = () -> {
  Class<?> aClass;
  try {
   aClass = Class.forName(classPath);
   Object o = aClass.newInstance();
   Method[] declaredMethods = aClass.getDeclaredMethods();
   for (Method declaredMethod : declaredMethods) {
   if (declaredMethod.getName().equals(executeMehod)) {
    /// log.info("方法名称:{}",declaredMethod.getName());
    declaredMethod.invoke(o);
   }
   }
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  };
  CronTask cronTask = new CronTask(runnable, cron);
  ScheduledTask scheduledTask = taskRegistrar.scheduleCronTask(cronTask);
  //scheduledTask.cancel(); 取消定时任务

 }


 }


 @Data
 private static class TaskRecord {

 private String classPath;

 private String executeMehod;

 private String cron;

 //可以在增加一个type 执行其他类型的定时任务
 }
}

微信公众号
技术图片
JAVA程序猿成长之路
分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。

SpringBoot基于数据库的定时任务统一管理

标签:ddc   font   资源   acl   object   work   lombok   tst   增加   

热心网友

1) Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。 最早的时候就是这样写定时任务的。
2) 开源的第三方框架: Quartz 或者 elastic-job , 但是这个比较复杂和重量级,适用于分布式场景下的定时任务,可以根据需要多实例部署定时任务。
3) 使用Spring提供的注解: @Schele 。 如果定时任务执行时间较短,并且比较单一,可以使用这个注解。
案例:
@SpringBootApplication
/*
* 开启对定时任务的支持
* 在相应的方法上添加@Scheled声明需要执行的定时任务。
*/
@EnableScheling
//@EnableScheling注解来开启对计划任务的支持
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@Component
public class ScheledTasks {

private Logger logger = LoggerFactory.getLogger(ScheledTasks.class);

private int i=0;
//0 0 0 2 * ?
@Scheled(cron="* * * 2 * ?")
//@Scheled 注解用于标注这个方法是一个定时任务的方法
public void testFixDelay() {
logger.info("执行方法"+i++);
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com