Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java scheduleAtFixedRate stops working after 2 times

I have this code:

    exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
          System.err.println("Getting messages....");
          getNewMessagesAndAddToTextArea();
      }
    }, 0, GET_MESSAGE_INTERVAL, TimeUnit.SECONDS);

exec is in my class declared as: private ScheduledExecutorService exec;

I'm getting the "Getting messages...." messages 2 times and then it stops. I can't explain why. The GUI is still working. So what happened here?


1 Answers

I suspect getNewMessagesAndAddToTextArea is throwing an exception.

The first way to validate that idea is to add

System.err.println("Finished getting messages");

at the end of your run method. If (as I expect) you don't see that the second time, you should consider including a try/catch block which logs exceptions. You'll need to think what you want to do with uncaught unchecked exceptions...

like image 182
Jon Skeet Avatar answered Jul 14 '26 23:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!