数据库动态定时任务


基于SpringBoot + MySQL数据库实现动态定时任务

项目代码https://gitee.com/git870845084/scheduled.git

一、MySQL中新建task表

DROP TABLE IF EXISTS `task`;
CREATE TABLE `task`  (
  `task_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `task_cron` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'cron表达式',
  `task_class_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '类路径',
  `task_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
  `task_description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
  `task_enable` int(2) NOT NULL COMMENT '1/0   启动/关闭',
  PRIMARY KEY (`task_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

插入数据

INSERT INTO `task` VALUES ('1', '0/5 * * * * ?', 'com.scheduled.task.LogTask', '日志打印', NULL, 1);
INSERT INTO `task` VALUES ('2', '0/10 * * * * ?', 'com.scheduled.task.TestTask', '测试任务', NULL, 1);

Cron表达式参数:* * * * * *
秒(0~59)如:0/5表示每5秒
分(0~59)
时(0~59)
月的某天(0~31)需计算
月(0~11)
周几(1~7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

二、新建一个SpringBoot项目

1.添加maven坐标

在pom.xml中添加maven坐标

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

2.添加配置信息

application.properties

server.port=80

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=666666

logging.level.com.example.demo.dao=debug

3.任务调度配置类

package com.scheduled.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class ScheduledConfig {

	@Bean
	public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
		ThreadPoolTaskScheduler poolTaskScheduler = new ThreadPoolTaskScheduler();
		poolTaskScheduler.setThreadNamePrefix("task-");
		return poolTaskScheduler;
	}
	
}

4.任务调度触发器

package com.scheduled.trigger;

import java.util.Date;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;

public class ScheduledTrigger implements Trigger {
	
	private String cron;
	
	@SuppressWarnings("unused")
	private ScheduledTrigger() {}
	
	public ScheduledTrigger(String cron) {
		this.cron = cron;
	}

	@Override
	public Date nextExecutionTime(TriggerContext triggerContext) {
		CronTrigger cronTrigger = new CronTrigger(cron);
		Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
		return nextExecutionTime;
	}

}

5.任务调度组件用来开启/关闭/重启计划任务

package com.scheduled.dynamic;

import java.util.Collection;
import java.util.concurrent.ScheduledFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.scheduled.domain.TaskEntity;
import com.scheduled.task.AbstractTask;
import com.scheduled.trigger.ScheduledTrigger;

@Component
public class DynamicScheduleTask {
	
	@Autowired
	private ThreadPoolTaskScheduler threadPoolTaskScheduler;

	//关闭所有任务
	public void shutDown() {
		Collection<ScheduledFuture<?>> values = SingletonFuture.getInstance().getFutureMap().values();
		for(ScheduledFuture<?> future:values) {
			if (future != null) {
				future.cancel(true);
			}
		}
		SingletonFuture.getInstance().getFutureMap().clear();
	}
	
	public void start(AbstractTask task,TaskEntity entity) {
		ScheduledTrigger trigger = new ScheduledTrigger(entity.getTask_cron());
		ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(task, trigger);
		String className = entity.getTask_class_name();
		SingletonFuture.getInstance().getFutureMap().put(className, future);
	}
	
	public void stop(String className) {
		if(!StringUtils.isEmpty(className)) {
			ScheduledFuture<?> future = SingletonFuture.getInstance().getFutureMap().get(className);
			if (future != null) {
				future.cancel(true);
				SingletonFuture.getInstance().getFutureMap().remove(className);
			}
		}
	}
	
	public void restart(AbstractTask task,TaskEntity entity) {
		stop(entity.getTask_class_name());
		start(task, entity);
	}
	
}

任务缓存类

package com.scheduled.dynamic;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

public class SingletonFuture {
	
	private static volatile SingletonFuture ONLY;
	
	private Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<String, ScheduledFuture<?>>();
	
	private SingletonFuture() {}
	
	public static SingletonFuture getInstance() {
		if(null == ONLY) {
			synchronized(SingletonFuture.class) {
				if(null == ONLY) {
					ONLY = new SingletonFuture();
				}
			}
		}
		return ONLY;
	}

	public Map<String, ScheduledFuture<?>> getFutureMap() {
		return futureMap;
	}

	public void setFutureMap(Map<String, ScheduledFuture<?>> futureMap) {
		this.futureMap = futureMap;
	}

}

6.需要执行的任务

任务父类

package com.scheduled.task;

public abstract class AbstractTask implements Runnable {
	
}

计划打印日志类

package com.scheduled.task;

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

public class LogTask extends AbstractTask {

	@Override
	public void run() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		System.out.println(date+" --- : i come");
	}

}

计划测试类

package com.scheduled.task;

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

public class TestTask extends AbstractTask {

	@Override
	public void run() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());
		System.out.println(date+" --- : test");
	}

}

7.domain实体

package com.scheduled.domain;

public class TaskEntity {
	
	private String task_id;
	
	private String task_cron;
	
	private String task_class_name;
	
	private String task_name;
	
	private String task_description;
	
	private Integer task_enable;

	public String getTask_id() {
		return task_id;
	}

	public void setTask_id(String task_id) {
		this.task_id = task_id;
	}

	public String getTask_cron() {
		return task_cron;
	}

	public void setTask_cron(String task_cron) {
		this.task_cron = task_cron;
	}

	public String getTask_class_name() {
		return task_class_name;
	}

	public void setTask_class_name(String task_class_name) {
		this.task_class_name = task_class_name;
	}

	public String getTask_name() {
		return task_name;
	}

	public void setTask_name(String task_name) {
		this.task_name = task_name;
	}

	public String getTask_description() {
		return task_description;
	}

	public void setTask_description(String task_description) {
		this.task_description = task_description;
	}

	public Integer getTask_enable() {
		return task_enable;
	}

	public void setTask_enable(Integer task_enable) {
		this.task_enable = task_enable;
	}

	@Override
	public String toString() {
		return "TaskEntity [task_id=" + task_id + ", task_cron=" + task_cron + ", task_class_name=" + task_class_name
				+ ", task_name=" + task_name + ", task_description=" + task_description + ", task_enable=" + task_enable
				+ "]";
	}
	
}

8.DAO层

package com.scheduled.dao.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.scheduled.domain.TaskEntity;

@Mapper
public interface TaskMapper {
	
	@Select("SELECT task_id,task_cron,task_class_name,task_name,task_description,task_enable FROM task WHERE task_enable = 1")
	List<TaskEntity> findAll();
	
	@Select("SELECT task_id,task_cron,task_class_name,task_name,task_description,task_enable FROM task WHERE task_class_name=#{task_class_name}")
	TaskEntity getTaskEntity(String task_class_name);

	@Select("SELECT task_cron FROM task WHERE task_id=#{task_id}")
	String getTaskCronById(String task_id);
	
}

9.SERVICE层

package com.scheduled.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.scheduled.dao.mapper.TaskMapper;
import com.scheduled.domain.TaskEntity;

@Service
public class TaskService {
	
	@Autowired
	private TaskMapper taskMapper;
	
	public List<TaskEntity> findAll() {
		List<TaskEntity> tasks = taskMapper.findAll();
		if(tasks.isEmpty()) {
			throw new RuntimeException("查询异常");
		}
		return tasks;
	}
	
	public TaskEntity getTaskEntity(String className) {
		TaskEntity task = taskMapper.getTaskEntity(className);
		if(null == task) {
			throw new RuntimeException("查询异常");
		}
		return task;
	}

	public String getTaskCronById(String task_id) {
		String cron = taskMapper.getTaskCronById(task_id);
		if(StringUtils.isEmpty(task_id)) {
			throw new RuntimeException("查询异常");
		}
		return cron;
	}

}

10.WEB层

package com.scheduled.controll;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.scheduled.domain.TaskEntity;
import com.scheduled.dynamic.DynamicScheduleTask;
import com.scheduled.service.TaskService;
import com.scheduled.task.AbstractTask;

@RestController
public class CronContrll {

	@Autowired
	private DynamicScheduleTask scheduleTask;
	
	@Autowired
	private TaskService taskService;
	
	@GetMapping("startAll")
	public void startAll() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		List<TaskEntity> taskEntitys = taskService.findAll();
		for(TaskEntity entity:taskEntitys) {
			Object newInstance = Class.forName(entity.getTask_class_name()).newInstance();
			AbstractTask task = (AbstractTask) newInstance;
			scheduleTask.start(task, entity);
		}
	}
	
	@GetMapping("shutDown")
	public void shutDown() {
		scheduleTask.shutDown();
	}
	
	@GetMapping("start/{className}")
	public void start(@PathVariable("className") String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		TaskEntity entity = taskService.getTaskEntity(className);
		Object newInstance = Class.forName(className).newInstance();
		AbstractTask task = (AbstractTask) newInstance;
		scheduleTask.start(task, entity);
	}

	@GetMapping("stop/{className}")
	public void stop(@PathVariable("className") String className) {
		scheduleTask.stop(className);
	}
	
	@GetMapping("restart/{className}")
	public void restart(@PathVariable("className") String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		TaskEntity entity = taskService.getTaskEntity(className);
		Object newInstance = Class.forName(className).newInstance();
		AbstractTask task = (AbstractTask) newInstance;
		scheduleTask.restart(task, entity);
	}

}

运行结果
在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过使用Spring的任务调度框架和Spring的JdbcTemplate来实现根据数据库动态设置定时任务。 首先,需要定义一个定时任务执行的接口,例如: ```java public interface JobInterface { void execute(); } ``` 然后,创建一个任务调度类,用于定时执行任务。在这个类中,可以通过JdbcTemplate查询数据库,获取需要执行的任务列表,并动态添加定时任务。例如: ```java @Component public class JobScheduler { private final TaskScheduler scheduler; private final JdbcTemplate jdbcTemplate; @Autowired public JobScheduler(TaskScheduler scheduler, JdbcTemplate jdbcTemplate) { this.scheduler = scheduler; this.jdbcTemplate = jdbcTemplate; } @PostConstruct public void scheduleJobs() { List<JobEntity> jobList = jdbcTemplate.query("SELECT * FROM job", new BeanPropertyRowMapper<>(JobEntity.class)); for (JobEntity job : jobList) { scheduler.schedule(new Runnable() { @Override public void run() { try { // 获取任务类名 Class<?> clazz = Class.forName(job.getClassName()); // 获取任务执行器 JobInterface jobInterface = (JobInterface) clazz.newInstance(); // 执行任务 jobInterface.execute(); } catch (Exception e) { e.printStackTrace(); } } }, new CronTrigger(job.getCron())); } } } ``` 其中,JobEntity是数据库中存储的任务实体类,包含任务类名和任务执行时间表达式。在scheduleJobs方法中,通过JdbcTemplate查询数据库获取任务列表,然后遍历任务列表,动态添加定时任务。当定时任务被触发时,会执行任务类中的execute方法。 需要注意的是,在执行任务类的时候需要使用反射机制获取任务类的实例,并调用execute方法执行任务

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值