Java Programing laungage

java.util Projects

java.util Project 1

Scheduling to Timer Task

In this page of the tutorials, we shall be learn how to schedule a timer task to run at a certain time and repeatedly. There is an example given for the description.

Previous Home Next
adplus-dvertising

This program will be ask you for the way of performing the task whether at the certain time or repeatedly. If we are enter the "c" then the program will perform the timer task at a certain time means the task will work only once while we enter the "r" then the program performs the timer task repeatedly until you terminate the program.

Code Description

This program has used the following method.

Timer.schedule()

This method of Timer class is used to set the schedule for the specific task. In this program, this method has been used two times. In this program First time passed The two parameters through the method.

  • Task which has to be performed.

  • Time for the first time perform the task.

Second time three parameters have passed in the method.

  • Time period in which the task has to be repeated.

Example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class scheduletimertasks {
public static void main(String[] args) throws IOException{
int delay = 1000;
Timer timer = new Timer();
System.out.println("What do you want (Time Creation or time Repeat)?");
System.out.print("Please enter \'C\' or \'R\' for Choice: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String ans = br.readLine();
if (ans.equals("C") || ans.equals("c")){
timer.schedule(new TimerTask(){
public void run(){
System.out.println("This is printed only once.");
}
},delay);
}
else if(ans.equals("r") || ans.equals("R")){
timer.schedule(new TimerTask(){
public void run(){
System.out.println("This is printed repeatedly.");
}
},delay, 1000);
}
else{
System.out.println("Invalid Entry.");
System.exit(0);
}
System.exit(0);
}
}

Previous Home Next