Search code examples
javaswingtimerswingworker

Java: Swing Timer waiting


I have such a code:

final SwingWorker worker = new SwingWorker() { 
      @Override
      protected Object doInBackground() throws Exception {...};
}
Timer timer=new Timer(10000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            worker.execute(); 
        }
    });
    timer.start();

Sometimes worker procedure takes more than 10 seconds, but sometimes 3-4sec, so how to set the timer to wait for the full execution of worker ? Any suggestions?


Solution

  • See the javadoc of the SwingWorker class:

    Before the doInBackground method is invoked on a worker thread, SwingWorker notifies any PropertyChangeListeners about the state property change to StateValue.STARTED. After the doInBackground method is finished the done method is executed. Then SwingWorker notifies any PropertyChangeListeners about the state property change to StateValue.DONE.

    So events are fired when the SwingWorker is done. Attach a listener and re-activate your Timer on the correct event.