Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print "hello world" every X seconds

Tags:

java

timer

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?

like image 794
meiryo Avatar asked Oct 16 '12 05:10

meiryo


People also ask

What is timer in Java?

A Timer in Java is a process that enables threads to schedule tasks for later execution. Scheduling is done by keeping a specific process in the queue such that when the execution time comes, the processor can suspend other processes and run the task.


2 Answers

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); 
like image 162
Tim Bender Avatar answered Oct 12 '22 03:10

Tim Bender


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); 
like image 24
Rohit Jain Avatar answered Oct 12 '22 02:10

Rohit Jain