Say:
package com.sdkj.demo.schedule;
import java.util.Date;
public class Say implements Runnable {
@Override
public void run(){
System.out.println("" + new Date() + " hello");
}
}
ScheduleController:
package com.sdkj.demo.controller;
import com.sdkj.demo.schedule.Say;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
@Controller
public class ScheduleController {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
return new ThreadPoolTaskScheduler();
}
private ScheduledFuture<?> future;
@PostMapping("/startCron")
@ResponseBody
public String startCron(@RequestBody(required = false) Map<String,String> map){
//threadPoolTaskScheduler.shutdown();
future = threadPoolTaskScheduler.schedule(new Say(), new CronTrigger(map.get("core")));
return "开始定时任务";
}
@RequestMapping("/stopCron")
@ResponseBody
public String stopCron(){
if(future != null) {
future.cancel(true);
}
return "停止定时任务";
}
}
post -> http://127.0.0.1:8080/startCron {"core":"0 0/1 * * * ? "}
post -> http://127.0.0.1:8080/stopCron