At a particular point of time every developer needs to run some task background. In java we have background clean up program nothing but Garbage Collection.
This simple thread is very easy to implement. Create a thread and put it in a while loop to execute forever. This will run the thread forever at back end. Provide thread methods to provide interval for running.
Every developer can achieve these background tasks by using java threads concepts.
They are as follows,
- using Simple Thread
- using ScheduledExecutorService
- using timer task
Using Simple Thread :
public class SimpleThreadTask{ public static void main(String[] args) { // run in for every 10 seconds final long timeInterval = 10000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- YOur code to run a task System.out.println("Hello !!"); // ------- ends code try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } }
Using ScheduledExecutorService:
This ScheduledExecutorService is provide in Java 5.