Scheduled Executor Service is only running once, no exceptions are thrown

597 views Asked by At

This code should run indefinitely. However, it successfully runs once and then never again. No exceptions are throw so I can't figure out what I did wrong. However, when nextExpression is not called, it does run indefinitely.

Here is the code:

onCreate() {

    Runnable Runnable = new Runnable() {
        public void run() {
            System.out.println("Hello world");
            nextExpression();
        }
    };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(Runnable, 0, 3, TimeUnit.SECONDS);
}


int i = 0;

public void nextExpression() {
    i++;
    expression.setText("" + i);
}
2

There are 2 answers

0
ddarellis On BEST ANSWER

I tested and it runs as it should, if you want to update a UI component you should do it with the main thread.

To update the textView from the Main thread you can do it like this:

public void nextExpression() {
    i++;
    runOnUiThread(new Runnable() {
        public void run() {
            expression.setText("" + i);
        }
    });
}
0
Oleg Bogdanov On

Your UI update is not happening on UI thread but on threadpool thread, that won't work. To relay update to UI thread modify

expression.setText("" + i);

to

expression.post(new Runnable() {
            @Override
            public void run() {
                expression.setText("" + i);
            }
        });