创建 ApplicationContextHelper
package com.example.demo.test;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public ApplicationContextHelper() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHelper.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext != null?applicationContext.getBean(beanName):null;
}
}
创建dao层
package com.example.demo.test;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface ScheduleDao {
@Select("select * from schedule_task ")
List<ScheduleEntity> getScheduleList();
}
创建实体类
package com.example.demo.test;
/**
* @program: teak-damo
* @author: xlk
*/
public class ScheduleEntity {
private Long id;
private String job ;
private String names ;
private String method;
private String cron;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
}
创建service
package com.example.demo.test;
public interface Scheduleservice {
}
创建service实现类(定时任务执行的逻辑)
package com.example.demo.test;
import org.springframework.stereotype.Service;
/**
* @program: teak-damo
* @author: xlk
*/
@Service
public class ScheduleserviceImpl implements Scheduleservice{
public void test1(){
System.out.println(" 定时任务执行逻辑 111 ");
}
public void test2(){
System.out.println(" 定时任务执行逻辑 222 ");
}
}
定时任务核心功能类 ScheduleTaskConfig
package com.example.demo.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
/**
* @program: teak-damo
* @author: xlk
*/
@Component
public class ScheduleTaskConfig implements SchedulingConfigurer {
@Autowired
private ScheduleDao scheduleDao;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
// 获取所有任务
List<ScheduleEntity> scheduleList = scheduleDao.getScheduleList();
System.out.println(scheduleList.size());
for (ScheduleEntity s : scheduleList){
scheduledTaskRegistrar.addTriggerTask(getRunnable(s), getTrigger(s));
}
}
/**
* 转换首字母小写
*
* @param str
* @return
*/
public static String lowerFirstCapse(String str) {
char[] chars = str.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
/**
* 添加任务
* @param scheduleEntity
* @return
*/
private Runnable getRunnable(ScheduleEntity scheduleEntity){
return new Runnable() {
@Override
public void run() {
Class<?> clazz;
try {
clazz = Class.forName(scheduleEntity.getNames());
String className = lowerFirstCapse(clazz.getSimpleName());
Object bean = (Object) ApplicationContextHelper.getBean(className);
Method method = ReflectionUtils.findMethod(bean.getClass(), scheduleEntity.getMethod());
ReflectionUtils.invokeMethod(method, bean);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
};
}
/**
* Trigger
* @param scheduleEntity
* @return
*/
private Trigger getTrigger(ScheduleEntity scheduleEntity){
return new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger trigger = new CronTrigger(scheduleEntity.getCron());
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
};
}
}
没有添加对定时任务修改的功能,需要自己去数据库手动修改添加数据,也可以自行添加、修改功能(很简单)
springboot启动类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
配置链接数据库 application.properties
server.port=8083
spring.datasource.url:jdbc:mysql://192.168.1.215:3306/task_demo?useSSL=false
spring.datasource.username:root
spring.datasource.password:root
添加数据库表结构和数据
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for schedule_task
-- ----------------------------
DROP TABLE IF EXISTS `schedule_task`;
CREATE TABLE `schedule_task` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`names` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`method` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`cron` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`status` int(2) NULL DEFAULT NULL COMMENT '0 代表开启,1代表关闭',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
代注释语句
CREATE TABLE `schedule_task` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',
`job` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '任务名称',
`names` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '任务全部类路径',
`method` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '方法名',
`cron` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '表达式',
`status` int DEFAULT NULL COMMENT '0 代表开启,1代表关闭',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Records of schedule_task
-- ----------------------------
INSERT INTO `schedule_task` VALUES (1, 'ces1 ', 'com.example.demo.test.ScheduleserviceImpl', 'test1', '0/5 * * * * ?', 1);
INSERT INTO `schedule_task` VALUES (2, 'ces2 ', 'com.example.demo.test.ScheduleserviceImpl', 'test2', '0/5 * * * * ?', 1);
SET FOREIGN_KEY_CHECKS = 1;
打印日志
demo地址:
链接:https://pan.baidu.com/s/1EhqwLqwIO4UcO4CBxBDObw
提取码:1234