In some applications some task need to run periodically, for example a application of report generating checks for new database entry after one day and make reports according to the entries then save all entries in company's permanent record.
Task Scheduling in JAVA
In some applications some task need to run periodically, for example a application of report generating checks for new database entry after one day and make reports according to the entries then save all entries in company's permanent record.
Java provide facility to schedule tasks as per requirement. This is example given below to schedule a simple task to display a message after 3 seconds.
Methods and classes used in this example :
java.util.TimerTask class specifies a task that can be scheduled to run once or after scheduled time. We can define action to be performed by this timer task. by using run() method of java.util.TimeTask. This is protected method.
java.util.Timer class provides facility to schedule tasks for future execution in a background thread. In this example we have used schedule() method of this class that specifies task for execution after the specified delay. It takes time delay as a parameter in milliseconds.
Note : Use ctrl + C to exit from this program.
TaskScheduling.java
import java.util.*; class Task extends TimerTask { int count = 1; // run is a abstract method that defines task performed at scheduled time. public void run() { System.out.println(count+" : Mahendra Singh"); count++; } } class TaskScheduling { public static void main(String[] args) { Timer timer = new Timer(); // Schedule to run after every 3 second(3000 millisecond) timer.schedule( new Task(), 3000); } }
Output of the program :