• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to stop/cancel a scheduled task ScheduledFuture/ThreadPoolTaskScheduler

 
Angie Kimura
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am able to call the start() function to run this QuarterlyMetricReportSchedulingService 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 * 10 * 1000;

@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();
}


}
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The schedule() method returns a scheduled future ( http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledFuture.html?is-external=true )
http://static.springsource.org/spring/docs/3.2.2.RELEASE/spring-framework-reference/htmlsingle/#scheduling-task-scheduler

You need to keep a handle to this future (you get it in your start() method) somewhere so that when you need to cancel the job you can then call cancel on the ScheduledFuture.

Also you do not need to shutdown the entire executor that will kill everything.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic