背景
对于一些不那么复杂的定时任务,好像也没必要上一整套xxl-job或者quartz之类的,自己简单实现一套也行
环境
- jdk 21
- Springboot 2.7.18
- nacos
目标
- 可以通过@EnableScheduling和比较简单的任务注册使用定时任务
- 定时任务的运行间隔可以通过nacos配置动态刷新
- 任务可以通过配置一键启停
代码
nacos配置
我这里把任务抽象出来单独配置在nacos:
scheduler:
tasks:
- name: test1
cron: 0/5 * * * * ?
desc: 测试1
enabled: true
- name: test2
cron: 0/10 * * * * ?
desc: 测试2
enabled: false
Springboot配置
我这里是希望注入比较简单,如果你不喜欢也可以直接array注入,都一样的
@Component
@ConfigurationProperties(prefix = "scheduler")
public class SchedulerTasksNacosConfig extends ScheduleTasks {
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ScheduleTasks {
private List<ScheduledTaskDto> tasks;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class ScheduledTaskDto {
private String name;
private String cron;
private String desc;
private boolean enabled;
}
}
开始准备定时任务
接口
public interface SchedulerTaskService {
/**
* 获取任务ID
*
* @return 任务ID
*/
String getTskId();
/**
* 获取任务
*
* @return 任务
*/
Runnable getTask();
}
实际任务1
测试通过分布式锁确保一个时间点只有一个任务可执行
@Service
@Slf4j
public class Test1Task implements SchedulerTaskService {
@Resource
private LockUtil lockUtil;
@Override
public String getTskId() {
return "test1";
}
@Override
public Runnable getTask() {
return () -> {
final String lockKey = getTskId();
final String lockVal = lockUtil.tryLock(lockKey);
if (StringUtils.isEmpty(lockVal)) {
log.warn("任务-{} 尝试获取分布式锁失败,可能有其他实例正在执行该任务", getTskId());
return; // 如果获取锁失败,直接返回
}
try {
System.out.println("正常获得锁,执行测试1任务");
} finally {
lockUtil.unlock(lockKey, lockVal); // 确保在任务执行完毕后释放锁
}
};
}
实际任务2
@Service
public class Test2Task implements SchedulerTaskService {
@Override
public String getTskId() {
return "test2";
}
@Override
public Runnable getTask() {
return () -> System.out.println("任务2开始执行:" + new Date());
}
}
注册并执行任务
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;
@Configuration
@EnableScheduling
@RefreshScope
public class DynamicScheduleConfig {
@Autowired
private SchedulerTasksNacosConfig schedulerTasksNacosConfig;
@Autowired
private List<SchedulerTaskService> schedulerTaskServices;
private ThreadPoolTaskScheduler scheduler;
private final Map<String, ScheduledFuture<?>> futureMap = new HashMap<>();
private final Map<String, Runnable> taskMap = new ConcurrentHashMap<>();
/**
* 类初始化,将所有定时任务都注册到Map中方便使用
*/
@PostConstruct
public void start() {
if (!CollectionUtils.isEmpty(schedulerTaskServices)) {
taskMap.putAll(
schedulerTaskServices.stream()
.collect(Collectors.toMap(SchedulerTaskService::getTskId, SchedulerTaskService::getTask))
);
}
scheduler = new ThreadPoolTaskScheduler();
scheduler.initialize();
scheduleAllTasks();
}
// 注册所有任务
private void scheduleAllTasks() {
List<ScheduleTasks.ScheduledTaskDto> tasks = schedulerTasksNacosConfig.getTasks();
for (ScheduleTasks.ScheduledTaskDto taskDto : tasks) {
// 跳过无效或关停的任务
if (Objects.isNull(taskDto) || StringUtils.isEmpty(taskDto.getCron()) || StringUtils.isEmpty(taskDto.getName()) || !taskDto.isEnabled()) {
continue;
}
scheduleTask(taskDto.getName(), taskDto.getCron(), taskMap.getOrDefault(taskDto.getName(), () -> System.out.println("没有找到对应任务")));
}
}
private void scheduleTask(String taskName, String cron, Runnable task) {
ScheduledFuture<?> future = scheduler.schedule(
task,
triggerContext -> new org.springframework.scheduling.support.CronTrigger(cron)
.nextExecutionTime(triggerContext)
);
ScheduledFuture<?> oldFuture = futureMap.put(taskName, future);
if (oldFuture != null) {
oldFuture.cancel(false);
}
}
@EventListener(RefreshScopeRefreshedEvent.class)
public void onRefresh() {
scheduleAllTasks();
}
// 类销毁前执行完最后的任务
@PreDestroy
public void destroy() {
for (ScheduledFuture<?> future : futureMap.values()) {
if (future != null) {
future.cancel(false);
}
}
if (scheduler != null) {
scheduler.shutdown();
}
}
}