This example show you how to create a simple class for scheduling a task using Timer
and TimerTask
class.
package org.kodejava.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample extends TimerTask {
private final DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
public static void main(String[] args) {
// Create an instance of TimerTask implementor.
TimerTask task = new TimerExample();
// Create a new timer to schedule the TimerExample instance at a
// periodic time every 5000 milliseconds (5 seconds) and start it
// immediately
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, new Date(), 5000);
}
/**
* This method is the implementation of a contract defined in the
* TimerTask class. This in the entry point of the task execution.
*/
public void run() {
// To make the example simple we just print the current time.
System.out.println(formatter.format(new Date()));
}
}
Here is the result printed by the code snippet above:
09:53:28 AM
09:53:33 AM
09:53:38 AM
09:53:43 AM
09:53:48 AM
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024