Monday, 8 July 2013
Wednesday, 3 July 2013
Timer & TimerTask in Java
Whenever
we are asked to code scheduled processes , immediately Thread comes
into our mind & dealing with threads is the most complex task to be
handled while coding , at least for me. And if maintaining a timer with
the help of a thread with the other thread processes makes me lil'bit
annoyed.
Thanks to Timer and TimerTask classes in Java.
A Timer is required whenever any task is to be performed after regular interval of time. You know what task is to be done. We code for that task which performs its operation after particular duration as per defined in the timer.
Lets say you need to know no. of users dropped over server which might be due to network breakdown. As a naive programmer , you'll try to run a task which is supposed to bring no. of users over server after every minute and will calculate and compare with the previous user count of previous minute for example the difference comes out to be more than 50% then an alarm should be raised. [getting user count is indeed not the optimized solution for the defined problem]
Now the above process defined need to be performed after every 1 minute . It will be a foolishness to start a thread after every single minute to perform this task. The correct solution lies in Timer & TimerTask Class.
For Example:
We are going to write a code to generate a clock , a clock whose time is to be calculated after every single second & is even made to print.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author vaibhav
*/
public class timerclass extends Timer {
int i=0;
timerclass()
{
init();
}
public void init()
{
/* below timer is schedule to count 30 seconds from
* current second of current minute.
* scheduleAtFixedRate method : Schedules the specified
* task for repeated fixed-rate execution,
* beginning after the specified delay. Subsequent executions takes
* place at approximately regular intervals, separated by the specified period.
*/
scheduleAtFixedRate(new RunTimer(), 1000, 1000);
/* initail delay = 1000 milliseconds = 1 second
* period = 1000 milliseconds = 1 second (interval)
*/
}
class RunTimer extends TimerTask
{
@Override
public void run() {
if(i<=30)
{
System.out.println(new Date().getSeconds());
i++;
}
else
{
/*Cancels this timer task
* calling this method from within
* the run method of a repeating timer task
* absolutely guarantees that the timer task will not run again.
* i.e. you have to again create the schedular for re-running
* the timer
*/
cancel();
System.out.println("End") ;
System.exit(0);
}
}
}
}
package Timer;
/**
*
* @author vaibhav
*/
public class calltimer {
public static void main(String... s)
{
// init() in constructor of timer class will schedule timer for clock
timerclass tc = new timerclass();
}
}
Now the above written code runs a clock for 30 seconds.
We made use of :
a) scheduleAtFixedRate(Timer Task task, long delay, long period) of Timer Class
b) boolean cancel() : stops the timer of scheduler , method of TimerTask Class
c) run() : we overrided the run method , which is defined as abstract method in TimerTask Class.
Thanks to Timer and TimerTask classes in Java.
A Timer is required whenever any task is to be performed after regular interval of time. You know what task is to be done. We code for that task which performs its operation after particular duration as per defined in the timer.
Lets say you need to know no. of users dropped over server which might be due to network breakdown. As a naive programmer , you'll try to run a task which is supposed to bring no. of users over server after every minute and will calculate and compare with the previous user count of previous minute for example the difference comes out to be more than 50% then an alarm should be raised. [getting user count is indeed not the optimized solution for the defined problem]
Now the above process defined need to be performed after every 1 minute . It will be a foolishness to start a thread after every single minute to perform this task. The correct solution lies in Timer & TimerTask Class.
For Example:
We are going to write a code to generate a clock , a clock whose time is to be calculated after every single second & is even made to print.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author vaibhav
*/
public class timerclass extends Timer {
int i=0;
timerclass()
{
init();
}
public void init()
{
/* below timer is schedule to count 30 seconds from
* current second of current minute.
* scheduleAtFixedRate method : Schedules the specified
* task for repeated fixed-rate execution,
* beginning after the specified delay. Subsequent executions takes
* place at approximately regular intervals, separated by the specified period.
*/
scheduleAtFixedRate(new RunTimer(), 1000, 1000);
/* initail delay = 1000 milliseconds = 1 second
* period = 1000 milliseconds = 1 second (interval)
*/
}
class RunTimer extends TimerTask
{
@Override
public void run() {
if(i<=30)
{
System.out.println(new Date().getSeconds());
i++;
}
else
{
/*Cancels this timer task
* calling this method from within
* the run method of a repeating timer task
* absolutely guarantees that the timer task will not run again.
* i.e. you have to again create the schedular for re-running
* the timer
*/
cancel();
System.out.println("End")
System.exit(0);
}
}
}
}
package Timer;
/**
*
* @author vaibhav
*/
public class calltimer {
public static void main(String... s)
{
// init() in constructor of timer class will schedule timer for clock
timerclass tc = new timerclass();
}
}
Now the above written code runs a clock for 30 seconds.
We made use of :
a) scheduleAtFixedRate(Timer
b) boolean cancel() : stops the timer of scheduler , method of TimerTask Class
c) run() : we overrided the run method , which is defined as abstract method in TimerTask Class.
Tuesday, 2 July 2013
Subscribe to:
Posts (Atom)