一、配置线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class AsyncTheadConfig {
@Bean("threadPoolTaskScheduler")
public ThreadPoolTaskScheduler getThreadPoolTaskScheduler(){
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(10);
executor.setThreadNamePrefix("ThreadPoolTaskScheduler-");
executor.initialize();
return executor;
}
}
二、建立需要运行的定时任务
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/index")
@RestController
public class IndexController1 {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@SuppressWarnings("rawtypes")
private ConcurrentHashMap<String, ScheduledFuture> futureMap = new ConcurrentHashMap<String, ScheduledFuture>();
@SuppressWarnings({ "rawtypes" })
@GetMapping("/insert/{uid}/{time}")
public Object insert(@PathVariable("uid") String uid, @PathVariable("time") String time){
TimerThread timerCollectData = new TimerThread(uid);
ScheduledFuture future = threadPoolTaskScheduler.schedule(timerCollectData, new CronTrigger("*/"+time+" * * * * ?"));
futureMap.put(uid, future);
return null;
}
@SuppressWarnings("rawtypes")
@GetMapping("/remove/{uid}")
public Object remove(@PathVariable("uid") String uid){
ScheduledFuture scheduledFuture = futureMap.get(uid);
if(scheduledFuture != null){
scheduledFuture.cancel(true);
boolean cancelled = scheduledFuture.isCancelled();
while (!cancelled) {
scheduledFuture.cancel(true);
System.out.println(uid + "取消中");
}
futureMap.remove(uid);
}
return null;
}
}
2.ok了!!!
