Using a timer to start SwingWorker?

The task that I need to perform includes requesting some data from an external server, performing some (rather lengthy) data processing, and then updating the GUI with the processing results. Since the server may be unresponsive, the task is well suited for SwingWorker: the doInBackground() method gets the results, and then the ready-made method updates the GUI.

I need this to happen every few seconds. I know that I can use the while and Thread.sleep loops and create a new SwingWorker after each sleep. But everything I read frowns using loops and sleep. I would like to use a timer, but:

  • Using a swing timer seems counterproductive; since they work on EDT, I would essentially have no reason to use SwingWorker doInBackground. If the server did not respond, the GUI would not respond.

  • Using java.util.Timer seems a bit wasteful: it seems to create a background thread for TimerTask (), and since I just create a SwingWorker to do the actual work, I essentially create a background thread that creates another background thread.

Can someone tell me what is the best solution? I would like to stick with SwingWorker as it is perfect for the task, but I would like to avoid using a while loop if I can help it.

thanks

+4
source share
4 answers

You can use ScheduledExecutorService :

 scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) // get a scheduled executor service with one thread ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // schedule the worker at an intervall of 5 seconds scheduler.scheduleAtFixedRate(myWorker, 0, 5, TimeUnit.SECONDS); 
+2
source

I don’t understand why you could not use Swing Timer to start Swing Worker. What have you tried?

+2
source

I think you are on the right track with SwingWorker. Now you need to look at its publishing and processing methods. As your processing progresses, you publish () the object from the background thread, then the process () method is called on the Swing (EDT) thread so that you can update gui.

Thus, there are no coordinates for timers and other threads.

There is a simple prime example in javadocs: http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

+1
source

How big is the collection of data that you retrieve? If it is rather small, I would completely separate the task of fetching / processing and displaying.

  • Use some kind of memory cache to store the last processed dataset.
  • Use javax.swing.Timer to update the GUI with cached data.
  • Use java.util.Timer to retrieve data from the database, process and update the cache.
  • Be careful of timing issues between two points in your cache. You do not want your swing timer to capture data while updating another timer.
0
source

All Articles