Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a task in ScheduledThreadPoolExecutor once I think it's completed

I have a ScheduledThreadPoolExecutor with which I schedule a task to run at a fixed rate. I want the task to be running with a specified delay for a maximum of say 10 times until it "succeeds". After that, I will not want the task to be retried. So basically I'll need to stop running the scheduled task when I want it to be stopped, but without shutting down the ScheduledThreadPoolExecutor. Any idea how I'd do that?

Here's some pseudocode -

public class ScheduledThreadPoolExecutorTest {   public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15);  // no multiple instances, just one to serve all requests    class MyTask implements Runnable   {     private int MAX_ATTEMPTS = 10;     public void run()     {       if(++attempt <= MAX_ATTEMPTS)       {         doX();         if(doXSucceeded)         {           //stop retrying the task anymore         }       }       else       {          //couldn't succeed in MAX attempts, don't bother retrying anymore!       }     }   }    public void main(String[] args)   {     executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorTest().new MyTask(), 0, 5, TimeUnit.SECONDS);   } } 
like image 900
mystarrocks Avatar asked Feb 15 '13 06:02

mystarrocks


People also ask

How to cancel a task in ExecutorService?

Learn to cancel a task submitted to an executor service if the task still has to be executed and/or has not been completed yet. We can use the cancel() method of Future object that allows making the cancellation requests.

Can I End Task Scheduler?

End an existing task from Task SchedulerYou can stop a running task from completing its actions by ending it. To do this, select the task and, under Selected Item, click or tap End.


1 Answers

run this test, it prints 1 2 3 4 5 and stops

public class ScheduledThreadPoolExecutorTest {     static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15); // no     static ScheduledFuture<?> t;      static class MyTask implements Runnable {         private int attempt = 1;          public void run() {             System.out.print(attempt + " ");             if (++attempt > 5) {                 t.cancel(false);             }         }     }      public static void main(String[] args) {         t = executor.scheduleAtFixedRate(new MyTask(), 0, 1, TimeUnit.SECONDS);     } } 
like image 54
Evgeniy Dorofeev Avatar answered Sep 19 '22 22:09

Evgeniy Dorofeev