[java] Print "hello world" every X seconds

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?

This question is related to java timer

The answer is


Add Thread.sleep

try {
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}

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!");
}

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();
    }
  }
}

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

Note: This will require a try/catch block.


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


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);
    }
  }

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.


The easiest way would be to set the main thread to sleep 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.


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 {

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();
    }
}

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

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.


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