Search code examples
javavaadinrunnableschedule

Execute method periodically in the Vaadin GUI toolkit


I need to execute a method of a class every 10 secons, but I need to do it in the main thread of execution because I have to update things in the screen.

I'm using a ScheduledExecutorService:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);

Runnable runnable= new Runnable() {
    public void run() {
        someStuff();
    }
};

Is this posible?


Solution

  • There is no direct counterpart for "main thread" in Vaadin, most of the application logic is run in a worker thread of your Servlet engine and you can't use or reserve that. Instead you should just modify the UI state with a proper locking. From version 7, you should most often use UI.access(Runnable) method, which executes your UI modifications with locking properly and automatically sends changes to the browser if a push connection or polling is used.

    You can use that with executor service. Deriving from you example it would be something like:

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    
        Runnable runnable= new Runnable() {
            public void run() {
                myUitoBeModified.access(() -> someStuff());
            }
        };
        executor.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);
    

    Note, that if your someStuff() method contains some long long execution, you'll probably get best results if you keep that out of UI.access(Runnable) method and put only the actual UI modification into the UI.access(Runnable) method.