Search code examples
javaswinganimationexecutorservicescheduledexecutorservice

How to stop working ScheduledExecutorService?


In my project I have a chart which can turn into an animation depending on if we click Start or Stop button. I can make it start, but I don't know how to stop it. Method shutdownNow() gives no result. How can I do this? Here is my code

public class Animation extends JPanel{
    // initializations
    ScheduledExecutorService scheduler = 
               Executors.newScheduledThreadPool(1);

    Animation(String s){
        // initialization of chart and adding XYSeries 
        this.add(chartPanel);   
    }

    public void go() {
        scheduler.scheduleAtFixedRate( (new Runnable() {

        @Override
        public void run() {
            double first;
            l = dataset.getSeries();

            while(true) {   
                first = (double)l.get(0).getY(0);
                for (int k = 0; k < l.get(0).getItemCount(); k++) {
                    if (k + 1 < l.get(0).getItemCount()) l.get(0).updateByIndex(k, l.get(0).getY(k+1));
                    else l.get(0).updateByIndex(k, first);
                }   
            }
            }

        }),  0, 5, MILLISECONDS);

    }

    public void stop() {
        scheduler.shutdownNow();
    }

}

Solution

  • (!Thread.currentThread().isInterrupted()) may be a solution

    but personally i would:

    • extract runner in method
    • stop runner by flipping a boolean
    • call scheduler.shutdownNow(); when needed (on close JPanel?)

    example:

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    boolean running;
    
    public void setup() {
       scheduler.scheduleAtFixedRate(runner(), 0, 5, TimeUnit.MILLISECONDS);
    
    }
    
    private Runnable runner() {
      return () -> {
    
        while (running) {
           try {
            //DO YOUR STUFF HERE
            System.err.println("RUNNING");
            Thread.sleep(500);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
       }
     };
    }
    
    public void go() {
      running = true;
    }
    
    public void stop() {
     running = false ;
    }
    
    public void shutdown() {
      scheduler.shutdownNow();
    }
    
    
    public static void main(String[] args) throws InterruptedException {
      Demo tasks = new Demo();
      tasks.setup();
      for (int i = 1; i <= 5; i++) {
        System.err.println("GO FOR IT " + i);
        tasks.go();
        Thread.sleep(2000);
        tasks.stop();
        Thread.sleep(1000);
      }
      tasks.shutdown();
    }