Reputation: 11
I am able to call the start()
function to run this Quarterly Metric Report Scheduling Service that implements Runnable to schedule a certain task, but I also need to be able to stop/cancel the scheduled tasks later in case I need to change the schedule time.
I have read many posts and tried several ways to make the stop()
function work, but no luck.
I guess my question can also be how can i find/retrieve the scheduled tasks and cancel them?
Would someone please help? Thanks a lot.
@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();
}
}
Upvotes: 1
Views: 4366
Reputation: 51501
It seems a bit strange that you only schedule your task in the stop method.
You need to schedule the task at start, keep the future as a handle, and then call cancel on the future in the stop method.
You should create a thread pool once and use it for all reports, otherwise there is no pooling.
Upvotes: 1