Follow by Email

Thursday, May 23, 2013

Multithreading - Scheduling tasks in Java

Java provides us a very good mechanism to schedule any tasks to be executed after a specified time for once or for each specified time period. Take a look at following example which will print a single line after given specified time. We can use this approach to write scheduled  routines who will refresh /recycle heavy resources in our applications (both server and client) .

public class TestTimerAndSechaduledTask {
      Timer timer = new Timer();
      //**interval after which the task will be executed
      int intervel=100;
      int period=100;
      private TestTimerAndSechaduledTask(){
            ScheduledClass scheduledClass = new ScheduledClass();
            //**will execute task after given intervel(when programe is executed)
            //**and then after after each time period specified
            timer.schedule(scheduledClass, intervel,period);
       * Class which will be used by timer to eecute any task
       * @author sajjad.paracha
      public class ScheduledClass extends TimerTask{

            public void run() {
                  System.out.println("======>timer task executed    ");
      public static void main (String args[]){
            TestTimerAndSechaduledTask testTimerAndSechaduledTask =new TestTimerAndSechaduledTask();

Example : I have defined such scheduled routine in a chating server which after specified time can get rid of extra useless resources on server such as logged out client sessions ,InputStreams,OupputStreams and client socket refrences.

No comments:

Post a Comment