In this example we will show two different methods to schedule a task to run periodically in Java.
Source Code
(1)Using Thread
package com.beginner.examples;
public class RunTaskPeriodicallyExample1 {
public static void main(String[] args) {
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
System.out.println("Hello !!");
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
Output:
Hello !!
Hello !!
Hello !!
Hello !!
(2)Using the Timer and TimerTask
package com.beginner.examples;
import java.util.Timer;
import java.util.TimerTask;
public class RunTaskPeriodicallyExample2 {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Hello !!!");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
timer.scheduleAtFixedRate(task, delay,intevalPeriod);
}
}
Output:
Hello !!
Hello !!
Hello !!
Hello !!
References
Imported packages in Java documentation: