2

I have to repeat a part of my code every 2 seconds how could I do that? don't tell me to use try { Thread.sleep(millisecondi); } catch (Exception e) {}

because freeze the application

user2864740
  • 60,010
  • 15
  • 145
  • 220
xSmog3s
  • 119
  • 1
  • 3
  • 8
  • If it "freezes the application" then it is probably Swing/AWT code attempting to use Thread.sleep on the EDT. Make sure to include appropriate context .. and [search first](http://stackoverflow.com/search?q=%5Bjava%5D+timer). – user2864740 Aug 13 '14 at 21:51

1 Answers1

18

If your application is to stay responsive you need to do this in another thread. Or you could simply create a timer and schedule it.

Whatever thread you're in when you tell it to sleep - will impeccably do so...

Something like this:

Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
    @Override
    public void run() {
        // whatever you need to do every 2 seconds
    }
};

timer.schedule(myTask, 2000, 2000);
Christoffer
  • 7,470
  • 9
  • 39
  • 55
  • I have to refresh a browser with this code browser.refresh(); but when there are a lot of errors:Exception in thread "Timer-1" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:4361) at org.eclipse.swt.SWT.error(SWT.java:4276) at org.eclipse.swt.SWT.error(SWT.java:4247) at org.eclipse.swt.widgets.Widget.error(Widget.java:468) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:359) – xSmog3s Aug 13 '14 at 22:21
  • @user3850946 Firstly, know that you are trying to do this within SWT would have been very useful. Secondly you need to do some reading up on currency in SWT. SWT will, violently, prevent you from access the UI from any thread other than it's Event Dispatching Thread – MadProgrammer Aug 14 '14 at 00:25