Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an action in periodic intervals in java?

Tags:

java

loops

timer

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).

like image 937
Sarang Avatar asked Jul 01 '13 04:07

Sarang


2 Answers

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.

like image 158
fmodos Avatar answered Oct 04 '22 12:10

fmodos


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);
    }
 }
like image 21
kosa Avatar answered Oct 04 '22 10:10

kosa