我可以调用该start()
函数来运行这个实现 Runnable 的 Quarterly Metric Report Scheduling Service 来调度某个任务,但我还需要能够在以后停止/取消已调度的任务,以防我需要更改调度时间。
我已经阅读了很多帖子并尝试了几种方法来使该stop()
功能正常工作,但没有运气。我想我的问题也可能是我如何找到/检索计划任务并取消它们?
有人可以帮忙吗?非常感谢。
@Configuration
@EnableScheduling
public class QuarterlyMetricReportScheduling{
@Autowired
QuarterlyMetricReportService qmrService;
ScheduledFuture sf;
CronTrigger trigger;
int shutdownTimeout = 1 * 60 * 1000;//10 sec
@Autowired
QuarterlyMetricReportSchedulingService task;
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler tps = new ThreadPoolTaskScheduler();
tps.setThreadNamePrefix("job");
return tps;
}
public void changeTrigger(String cronExpression){
System.out.println("change trigger to: " + cronExpression);
trigger = new CronTrigger(cronExpression);
start();
}
public void start(){
ThreadPoolTaskScheduler tps = new ThreadPoolTaskScheduler();
tps.initialize();
task = new QuarterlyMetricReportSchedulingService();
tps.schedule(task, trigger);
}
public void stop() {
ThreadPoolTaskScheduler tps = threadPoolTaskScheduler();
//tps = new ThreadPoolTaskScheduler();
//tps.setThreadNamePrefix("job");
tps.initialize();
task = new QuarterlyMetricReportSchedulingService();
trigger = new CronTrigger("0 59 11 26 3 ?");
tps.schedule(task, trigger);
ScheduledExecutorService scheduledExecutorService = tps.getScheduledExecutor();
try {
//ScheduledServiceExecutor service =
//Executors.newSingleThreadScheduledExecutor();
task = new QuarterlyMetricReportSchedulingService();
ScheduledFuture future = scheduledExecutorService.scheduleWithFixedDelay(
task, 1, 1, TimeUnit.MILLISECONDS);
future.cancel(true);
scheduledExecutorService.shutdown();
}
}