In Java, how would you create a function that prints out a string every 10 seconds?
In Java, how would you create a function that prints out a string every 10 seconds?
Below is the program to print string in every 10 seconds.
import java.util.TimerTask;
public class PrintHelper extends TimerTask {
int i = 0;
@Override
public void run() {
System.out.println("Timer ran " + ++i);
}
}
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new PrintHelper();
timer.schedule(task, 0, 10000);
}
}
Here I am using java Timer class to print string in every specified time.
Output:
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Timer ran 5
Timer ran 6
Timer ran 7
Timer ran 8
Comments
Post a Comment