151

Lately I've been using loops with large numbers to print out Hello World:

int counter = 0;

while(true) {
    //loop for ~5 seconds
    for(int i = 0; i < 2147483647 ; i++) {
        //another loop because it's 2012 and PCs have gotten considerably faster :)
        for(int j = 0; j < 2147483647 ; j++){ ... }
    }
    System.out.println(counter + ". Hello World!");
    counter++;
}

I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
meiryo
  • 11,157
  • 14
  • 47
  • 52
  • 1
    While the below answers should obviously answer your question, you should also note that the way you're doing it would result in a different interval on every machine. Depends on how fast it can run the compiler. – IHazABone Nov 20 '14 at 04:03
  • Possible duplicate of [Calling a function every 10 minutes](https://stackoverflow.com/questions/1220975/calling-a-function-every-10-minutes) – Alex Kulinkovich Jul 19 '17 at 15:58

14 Answers14

247

If you want to do a periodic task, use a ScheduledExecutorService. Specifically ScheduledExecutorService.scheduleAtFixedRate

The code:

Runnable helloRunnable = new Runnable() {
    public void run() {
        System.out.println("Hello world");
    }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • 14
    I hope somebody else upvotes this as well. Thread.sleep() might fit the code in the OP best, but it's a rather amateur reinvention of the wheel. Professional software engineers will use tried and trusted API, such as TimerTask. ScheduledExecutorService is even better, though; refer to Brian Goetz et al.'s _Java Concurrency in Practice_. The latter class has been around for nearly a decade—it's sad that all these other answers overlook it. – Michael Scheper Aug 14 '13 at 02:32
  • 3
    @MichaelScheper, Thank you, I'm glad to see that this answer has finally surpassed the `TimerTask` variant. Interestingly, I noticed that the accepted answer is actually not correct :\ The age of the two APIs aside, `ScheduledExecutorService` is simply more intuitively declarative. The use of `TimeUnit` as a parameter makes it much more clear what is occurring. Gone are the days of code like `5*60*1000 // 5 minutes`. – Tim Bender Feb 14 '14 at 18:39
  • 2
    @TimBender I noticed you have a 3 for the period argument. I cannot find whether that is in seconds or milliseconds. I would like to have it run every 500 milliseconds (half a second). – JohnMerlino Jun 20 '14 at 06:10
  • 2
    Ahh I see. Fourth argument lets you specify time e.g. TimeUnit.MILLISECONDS. – JohnMerlino Jun 20 '14 at 06:11
  • 3
    @TerryCarter In Java8+ You can instead do `Runnable helloRunnable = () -> { /*code */ };` which is even more beautiful ;) – Joel Apr 27 '19 at 08:48
211

You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.

You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..

Here's an example, which prints Hello World every 5 seconds: -

class SayHello extends TimerTask {
    public void run() {
       System.out.println("Hello World!"); 
    }
}

// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 10
    Note that the 2-param `schedule` method will execute once after the specified delay. The 3-param `schedule` or `scheduleAtFixedRate` would need to be used. – Tim Bender Feb 14 '14 at 18:42
  • 4
    @TimBender Just wondering whether OP really got his task done with this ;) Anyways, now I would prefer to use `ExecutorService` for these tasks. That is really a big improvement over traditional Thread API. Just didn't used it at the time of answering. – Rohit Jain Feb 14 '14 at 18:44
  • 5
    `Timer timer = new Timer(true);` should be set to `true` as a deamon. Unless You want timer still running after closing the application. – Tomasz Mularczyk Feb 20 '15 at 21:18
  • Keep in mind that this solution uses "fixed delays after completion of the previous task", which means that the delay starts once the previous cycle was completed. If the process was delayed (e.g garbage collection) then the timing will be off. If you want accuracy, for instance for long running threads, you should synchronize with the Date – keesp Mar 07 '19 at 09:33
  • after star this in eclipse how can stop this timer? Even i closed it run right? – Vijay Nov 07 '19 at 11:33
46

Try doing this:

Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 5000);

This code will run print to console Hello World every 5000 milliseconds (5 seconds). For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html

17

I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
tmwanik
  • 1,643
  • 14
  • 20
9

You can use Thread.sleep(3000) inside for loop.

Note: This will require a try/catch block.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
saum22
  • 884
  • 12
  • 28
  • 2
    I don't like this solution, I think it is a work around and not a real solution – vincenzopalazzo May 06 '21 at 21:23
  • I voted down this solution. You should never sleep a thread only to wait for the next thing to do. No matter the programming language, your program should do whatever needs and "keeps available" to the next thing that could show up. – Nat Feb 18 '22 at 19:06
7
public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}


public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}

infinite loop is created ad scheduler task is configured.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Vicky
  • 9,515
  • 16
  • 71
  • 88
5

The easiest way would be to set the main thread to sleep for 3000 milliseconds (3 seconds):

for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}
    System.out.println("Hello world!");
}

This will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. Take a look at the Thread#sleep doc:

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Benson Kiprono
  • 129
  • 1
  • 1
  • 12
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thanks @Luiggi. Java will always make sure it's 3000 ms no matter what machine (CPU) I run it on right? – meiryo Oct 16 '12 at 06:02
  • @NandkumarTekale care to elaborate more? – meiryo Oct 16 '12 at 06:03
  • 4
    @meiryo It will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. – Luiggi Mendoza Oct 16 '12 at 06:04
  • 4
    Caveat: if this is not a real time system, the sleep will be at least 3000 ms, but could be longer. If you want exactly 3000 ms sleep especially where human life is at risk (medical instruments, controlling planes etc.) you should use a real time operating system. – Kinjal Dixit Oct 16 '12 at 06:08
  • @LuiggiMendoza is there a solution where execution is not ceased? The hello world is just an example. I actually want to send a simple DatagramPacket from a UDP client to it's server every 3 seconds. Would `Thread.sleep` be appropriate? – meiryo Oct 16 '12 at 06:13
  • @meiryo if you're going to send info from the client to the server, then it's ok to use this method. You could use a `Timer` as others has suggested, but it will be up to you. – Luiggi Mendoza Oct 16 '12 at 06:23
  • You really shouldn't catch and ignore the InterruptedException in most code. At very least, re-interrupt the thread. – mjaggard Feb 11 '20 at 20:23
3

Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.

public class RemindTask extends TimerTask {
    public void run() {
      System.out.println(" Hello World!");
    }
    public static void main(String[] args){
       Timer timer = new Timer();
       timer.schedule(new RemindTask(), 3000,3000);
    }
  }
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2

This is the simple way to use thread in java:

for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(Exception e) {
        System.out.println("Exception : "+e.getMessage());
    }
    System.out.println("Hello world!");
}
julienc
  • 19,087
  • 17
  • 82
  • 82
1

What he said. You can handle the exceptions however you like, but Thread.sleep(miliseconds); is the best route to take.

public static void main(String[] args) throws InterruptedException {
leigero
  • 3,233
  • 12
  • 42
  • 63
1

Here's another simple way using Runnable interface in Thread Constructor

public class Demo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T1 : "+i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T2 : "+i);
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T3 : "+i);
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
User42
  • 970
  • 1
  • 16
  • 27
Mayur Chudasama
  • 584
  • 4
  • 8
0

Add Thread.sleep

try {
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}
Russell Gutierrez
  • 1,372
  • 8
  • 19
0

For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.

See tutorials for Quartz scheduling.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
-1
public class TimeDelay{
  public static void main(String args[]) {
    try {
      while (true) {
        System.out.println(new String("Hello world"));
        Thread.sleep(3 * 1000); // every 3 seconds
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}