要创建和管理多个动态安排的任务,
计划配置和bean:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
@Configuration
public class SchedulingConfigs implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
System.out.println("Running Schedular..." + Calendar.getInstance().getTime());
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Calendar nextExecutionTime = new GregorianCalendar();
Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
nextExecutionTime.add(Calendar.MILLISECOND, getNewExecutionTime());
return nextExecutionTime.getTime();
}
});
}
private int getNewExecutionTime() {
return 1000;
}
@Bean
public TaskScheduler poolScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
scheduler.setPoolSize(1);
scheduler.initialize();
return scheduler;
}
}
计划程序服务代码:
package io.loadium.resource.service;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
@Service
public class ScheduleTaskService {
TaskScheduler scheduler;
Map<Integer, ScheduledFuture<?>> jobsMap = new HashMap<>();
public ScheduleTaskService(TaskScheduler scheduler) {
this.scheduler = scheduler;
}
public void addTaskToScheduler(int id, Runnable task, Date runningDate) {
ScheduledFuture<?> scheduledTask = scheduler.schedule(task, runningDate);
jobsMap.put(id, scheduledTask);
}
public void removeTaskFromScheduler(int id) {
ScheduledFuture<?> scheduledTask = jobsMap.get(id);
if (scheduledTask != null) {
scheduledTask.cancel(true);
jobsMap.put(id, null);
}
}
@EventListener({ContextRefreshedEvent.class})
void contextRefreshedEvent() {
}
}
用法示例:
scheduleTaskService.addTaskToScheduler(1, () -> System.out.println("my task is running -> 1"), , Date.from(LocalDateTime.now().plusSeconds(10).atZone(ZoneId.systemDefault()).toInstant()));
scheduleTaskService.removeTaskFromScheduler(1);