feat: 动态调度
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.xiang.xservice.schedule.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
@Configuration
|
||||
public class DynamicTaskSchedulerConfig {
|
||||
@Bean
|
||||
public ThreadPoolTaskScheduler globalTaskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(10);
|
||||
scheduler.setThreadNamePrefix("task-scheduler-");
|
||||
scheduler.initialize();
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.xiang.xservice.schedule.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DynamicTaskSchedulerServiceImpl implements IDynamicTaskSchedulerService{
|
||||
|
||||
private final ThreadPoolTaskScheduler taskScheduler;
|
||||
|
||||
private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void schedule(String taskId, LocalDateTime runTime, Runnable task) {
|
||||
long delay = Duration.between(LocalDateTime.now(), runTime).toMillis();
|
||||
if (delay < 0) {
|
||||
throw new IllegalArgumentException("时间已过,无法调度");
|
||||
}
|
||||
|
||||
ScheduledFuture<?> future = taskScheduler.schedule(
|
||||
task, new Date(System.currentTimeMillis() + delay)
|
||||
);
|
||||
taskMap.put(taskId, future);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(String taskId) {
|
||||
ScheduledFuture<?> future = taskMap.get(taskId);
|
||||
if (future != null) {
|
||||
future.cancel(true);
|
||||
taskMap.remove(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean contains(String taskId) {
|
||||
return taskMap.containsKey(taskId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xiang.xservice.schedule.service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public interface IDynamicTaskSchedulerService {
|
||||
void schedule(String taskId, LocalDateTime runTime, Runnable task);
|
||||
void cancel(String taskId);
|
||||
Boolean contains(String taskId);
|
||||
}
|
||||
Reference in New Issue
Block a user