import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
@RestController
@RequestMapping("task")
public class TestController {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
public static Map<String, ScheduledFuture<?>> taskMap=new HashMap<>();
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
@RequestMapping("/is_start")
public boolean isStart() {
TestController.TaskThread tt=new TestController.TaskThread();
ScheduledFuture<?> future=taskMap.get("taskName");
if(future != null && !future.isCancelled()){
return true;
}else {
return false;
}
}
@RequestMapping("/start")
public String start() {
TestController.TaskThread tt=new TestController.TaskThread();
ScheduledFuture<?> future=threadPoolTaskScheduler.schedule(tt, new CronTrigger("0/5 * * * * *"));
taskMap.put("taskName", future);
System.out.println("开始");
return "start";
}
@RequestMapping("/stop")
public String stop() {
ScheduledFuture<?> future=taskMap.get("taskName");
if (future != null) {
future.cancel(true);
}
System.out.println("停止");
return "stop";
}
@RequestMapping("/change")
public String change() {
stop();// 先停止,在开启.
ScheduledFuture<?> future=taskMap.get("checkTask");
TestController.TaskThread tt=new TestController.TaskThread( );
future=threadPoolTaskScheduler.schedule(tt, new CronTrigger("*/10 * * * * *"));
System.out.println("修改");
return "changeCron";
}
//内部类
public class TaskThread implements Runnable {
@Override
public void run() {
//根据传来的参数执行要定时的任务
//...
}
}
@Component
public class ApplicationTask implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextStartedEvent) {
System.out.println("执行开机启动项目");
start();
}
}
}
基于ThreadPoolTaskScheduler的定时任务自动执行和手动开启关闭
最新推荐文章于 2024-05-08 09:36:50 发布