5

Is there any way of creating a loop that would do the task every 3 secs without using a sleep function

For eg:

try {
    while (true) {
        System.out.println(new Date());
        Thread.sleep(5 * 1000);
    }
} catch (InterruptedException e) {
    e.printStackTrace();
}

But the problem while using sleep function is that, it just freezes the program.

The main idea of this loop is to get a sync with mysql database (online).

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sarang
  • 83
  • 1
  • 3
  • 12

3 Answers3

7

Use java.util.TimerTask

java.util.Timer t = new java.util.Timer();
t.schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("This will run every 5 seconds");

            }
        }, 5000, 5000);

If you are using a GUI, you can use the javax.swing.Timer, example:

int delay = 5000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          System.out.println("This will run every 5 seconds");
      }
  };
  new javax.swing.Timer(delay, taskPerformer).start();

Some info about the difference between java.util.Timer and java.swing.Timer: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

fmodos
  • 4,472
  • 1
  • 16
  • 17
  • 1
    *"This will run every 3 seconds"* - No, it won't ;) and this also assumes that the user isn't using some kind of GUI framework – MadProgrammer Jul 01 '13 at 04:05
  • sysout fixed :) @MadProgrammer why you say that it assumes the user isn't using any GUI framework? is this why I didn't suggest to use `javax.swing.Timer`? – fmodos Jul 01 '13 at 04:09
  • 1
    There's no context to the question. If the OP is using Swing (for example), then is might not be a good idea. It is still a valid answer given the context, but I'd (personally) state that this assumes that the OP isn't using a GUI - IMHO – MadProgrammer Jul 01 '13 at 04:12
  • The programe is a GUI. @fmodos: It worked fine for me. But can you simplify the code for netbeans environment :) – Sarang Jul 01 '13 at 04:15
  • @user2471839 I am not sure what you mean by 'simplify the code for netbeans', this code doesn't use any third party library... so you just need to copy it into your code, anyway I will update the answer with an example of coding using the javax.swing.Timer as this is one GUI. – fmodos Jul 01 '13 at 04:22
  • @fmodos can you help me out with this part: http://stackoverflow.com/questions/17397442/how-to-check-if-a-jframe-is-opened – Sarang Jul 01 '13 at 04:27
  • @user2471839 no, I haven't coded GUI applications for a while... maybe someone else with more experience into that can help you. – fmodos Jul 01 '13 at 04:34
  • @fmodos i need the following statement to execute instead of : System.out.println("This will run every 5 seconds"); textarea.append("This will run every 5 seconds\n"); But the problem is, i cannot use the textarea because it is not created before. can you give me a suggestion to this problem – Sarang Jul 01 '13 at 04:59
  • @user2471839 You may find `SwingWorker` more suited to the task – MadProgrammer Jul 01 '13 at 05:16
4

You may use one of the implementation of ScheduledExecutorService if you are Ok to move logic which you want to execute repeatedly inside a thread.

Here is example from the link:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }
kosa
  • 65,990
  • 13
  • 130
  • 167
2

Are you using some kind of UI?

There are at least two timers available in Java;

Which should be capable of achieving what you want

There are also 3rd party libraries that might help as well

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366