动态定时任务

@Controller
@Component
@EnableScheduling
public class TestController {
//默认只能创建一个定时任务
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;


private HashMap<String, ScheduledFuture<?>> futureMap=new HashMap<>();

@Bean("threadPoolTaskScheduler")
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(20);
    return scheduler;
}
@RequestMapping("start")
@ResponseBody
public String start(String name,String cron){
    ScheduledFuture<?> schedule=threadPoolTaskScheduler.schedule(new myRunable(name), new CronTrigger(cron));
    futureMap.put(name,schedule);
    futureMap.forEach((key, value) -> {
        System.out.println(key + ":" + value);
    });
    return "startTest";
}
@RequestMapping("end")
@ResponseBody
public String end(String name){
    System.out.println(name);
    ScheduledFuture<?> schedule= futureMap.get(name);
    System.out.println(futureMap);
    if(schedule!=null){
        schedule.cancel(true);
        System.out.println("取消");
        System.out.println("endTask");
    }
    System.out.println(schedule);
    return "endTask";
}

 

 

public class myRunable implements Runnable{
    private String name;

    public myRunable(String name){
        this.name=name;
    }
    @Override
    public void run() {System.out.println(name);}
}

}

 

 

上一篇:nodejs模块 node-schedule使用,定时任务


下一篇:定时任务调度