Task scheduler is very important concept in today’s programming environment so I am discussing with you how we can implement a task scheduler in java.
Prior to discuss this you need to aware about the java’s java.util package. we use this package for our implementation. We require two important class of this package one is java.util.Timer and another is java.util.TimerTask.
Now we need to follow these steps.
1. Create a package scheduler.
2. Now in this package create a file MyTask.java and enter the following code.
package scheduler;
import java.util.Timer;
import java.util.TimerTask;
public class MyTask extends TimerTask{
Timer timer;
int count=0;
public MyTask(){
}
public MyTask(Timer timer){
this.timer=timer;
}
public void toDo(){
System.out.println("count-> "+(count++));
}
@Override
public void run() {
toDo();
if(count>10){//this is the condition when you want to stop the task.
timer.cancel();
}
}
}Note- the above java class extends java.util.TimerTask class this class have a abstract method run which we have to implement in our class. In this timer task class we implement a method toDo() which print the count value and increment it by 1 and in run method we call this method. In run() method we have a condition when we want to cancel the task in our case we cancel task when count value become greater tha 10 if you don’t want to stop the task then remove the condition in this case the task will run till then you don’t stop the application externally.
Here is one more thing we have constructor which have a parameter of java.util.Timer type this
parameter is use for cancel the task on any condition and for scheduling further.
3. Now we implement the main class for this we need to create the MyScheduler.java file. I create it in the same package in which I create the MyTask.java file and enter the following code.
package scheduler;
import java.util.Timer;
public class MyScheduler {
public MyScheduler() {
}
public static void main(String[] args){
Timer timer=new Timer();
MyTask myTask=new MyTask(timer);
int firstSart=1000;// it means after 1 second.
int period=1000*2;//after which the task repeat;
timer.schedule(myTask,firstSart,period);//the time specified in millisecond.
}
}Note- In this class we create main method and in the main method we create an object of java.util.Timer class and MyTask class which we implement above. we call the parametric consutructor of the class and pass the timer object to it. We create two variable firstStart and period. In firstStart we give the value in millisecond at which time we want to start the task and in the period we give the value at which time we want repeat the same task. Now we call the schedule method of the Timer class and pass the values to it.
4. It is done now compile the both file and run.
Note- In our sample program we use the simplest way to implement the task scheduler in java. Timer class have more schedule methods with different parameter so use these method accoding to you requirement.