Java – how do I stop the task in the scheduledthreadpoolexecutor once I think it is complete

I have a scheduledthreadpoolexecutor, and I schedule tasks to run at a fixed rate I want the task to run with the specified delay, up to 10 times, until "success" After that, I don't want the task to try again So basically I need to stop running the scheduled task when I want to stop it without closing the scheduledthreadpoolexecutor Any idea, what should I do?

Here are some pseudo code –

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(),5,TimeUnit.SECONDS);
  }
}

Solution

Run this test, print 1 2 3 4 5 and stop

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(),1,TimeUnit.SECONDS);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>