I am going to have to implement some functionality to my application soon that timesout a swing worker based on a user dictated length.
I was wondering if i could extend the swingworker class and add my own time out countdown inside, for example i could override the dowork method, call startCountdown() then call super.dowork and then keep checking if the timeout has been exceeded?
I was wondering if there were a better solution that this approach? Thanks
The javadocs for SwingWorker suggest this:
Because SwingWorker implements Runnable, a SwingWorker can be submitted to an Executor for execution.
This would be an easy solution for the timeout functionality you desire.
Submit your SwingWorker to ExecutorService#submit. On the resulting Future<?>, you may implement e.g. a timout of 10 seconds by
Future<?> f = service.submit(mySwingWorker);
try {
f.get(10, TimeUnit.SECONDS);
} catch (ExecutionException ex) {
/* SwingWorker threw an Exception */
} catch (TimeoutException ex) {
/* SwingWorker timed out */
} catch (InterruptedException ex) {
/* Thread got interrupted */
} catch (CancellationException ex) {
/* would only be thrown in case you
call #cancel on your future */
}
Use a Swing Timer ?
If it goes off, time is exceeded. Cancel it before that to stop it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With