spring手动设置定时任务
设置任务池配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class MultiTimerConfig implements SchedulingConfigurer {
@Bean(destroyMethod = "shutdown", name = "taskScheduler")
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setTaskScheduler(taskScheduler());
}
}
cron触发设置器
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;
public class TriggerImpl implements Trigger {
private String cronExpress;
public TriggerImpl(String cronExpress) {
this.cronExpress = cronExpress;
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger cronTrigger = new CronTrigger(cronExpress);
return cronTrigger.nextExecutionTime(triggerContext);
}
}
测试接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
@RestController
public class TPTSController {
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
private static Map<String, ScheduledFuture<?>> sm = new HashMap<>();
@RequestMapping(value = "/task/add")
public void addTask(@RequestParam(value = "taskName")String taskName){
ScheduledFuture<?> schedule = taskScheduler.schedule(new Task(), new TriggerImpl("0/5 * * * * ?"));
sm.put(taskName,schedule);
}
@RequestMapping(value = "/task/remove")
public void removeTask(@RequestParam(value = "taskName")String taskName){
ScheduledFuture<?> future = sm.get(taskName);
if (null != future && !future.isCancelled()){
future.cancel(true);
while (!future.isDone()) {
future.cancel(true);
}
}
sm.remove(taskName);
}
@RequestMapping(value = "/task/update")
public void updateTask(@RequestParam(value = "taskName")String taskName){
removeTask(taskName);
addTask(taskName);
}
class Task implements Runnable{
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+"----"+ LocalDateTime.now());
}
}
}