You have many options, some of them:
- Simple theme
- Timertask
- ScheduledExecutorService
Simple topic:
public class Task { public static void main(String[] args) { final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { System.out.println("Running Task ..."); try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } }
TimerTask:
import java.util.Timer; import java.util.TimerTask; public class Task { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { System.out.println("Running Task ..."); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1000; timer.scheduleAtFixedRate(task, delay,intevalPeriod); } }
ScheduledExecutorService:
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { System.out.println("Running Task ..."); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); } }
source share