An example, as you expected in this link
The timer will be started forever in our application until the application is closed or when the task or schedule is no longer available.
TimerTask is a task that has some functions that must be performed depending on time or duration.
In Timer, we will create a TimerTask to execute a specific duration or to start it to run at a specific duration.
Please understand how it works, apply with an applet or others.
1, the GCTask class extends the TimerTask class and implements the run () method.
2. In the TimerDemo program, a Timer object and a GCTask object are created.
3, using the Timer object, the task object is scheduled using the schedule () method of the Timer class to execute after a 5-second delay and then execute every 5 seconds.
4, an infinite while loop inside main () creates objects of type SimpleObject (the definition of which follows) that are immediately available for garbage collection.
import java.util.TimerTask; public class GCTask extends TimerTask { public void run() { System.out.println("Running the scheduled task..."); System.gc(); } } import java.util.Timer; public class TimerDemo { public static void main(String [] args) { Timer timer = new Timer(); GCTask task = new GCTask(); timer.schedule(task, 5000, 5000); int counter = 1; while(true) { new SimpleObject("Object" + counter++); try { Thread.sleep(500); } catch(InterruptedException e) {} } } } public class SimpleObject { private String name; public SimpleObject(String n) { System.out.println("Instantiating " + n); name = n; } public void finalize() { System.out.println("*** " + name + " is getting garbage collected ***"); } }
source share