Print "hello world" every X seconds

JavaTimer

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Note: This will require a try/catch block.

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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 {

Solution 11 - Java

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

Solution 12 - Java

Add Thread.sleep

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

Solution 13 - Java

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.

Solution 14 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmeiryoView Question on Stackoverflow
Solution 1 - JavaTim BenderView Answer on Stackoverflow
Solution 2 - JavaRohit JainView Answer on Stackoverflow
Solution 3 - Javauser4475555View Answer on Stackoverflow
Solution 4 - JavatmwanikView Answer on Stackoverflow
Solution 5 - Javasaum22View Answer on Stackoverflow
Solution 6 - JavaVickyView Answer on Stackoverflow
Solution 7 - JavaLuiggi MendozaView Answer on Stackoverflow
Solution 8 - JavaSubhrajyoti MajumderView Answer on Stackoverflow
Solution 9 - Javauser3928455View Answer on Stackoverflow
Solution 10 - JavaleigeroView Answer on Stackoverflow
Solution 11 - JavaMayur ChudasamaView Answer on Stackoverflow
Solution 12 - JavaRussell GutierrezView Answer on Stackoverflow
Solution 13 - JavaNandkumar TekaleView Answer on Stackoverflow
Solution 14 - Javauser3017805View Answer on Stackoverflow