• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1371
  • Last Modified:

Java Timer and TimerTask

I need to execute the timer.schedule command X number of times without using the sleep command.  For the first pass, seconds = 24, then seconds =  3, then seconds = 3 again.  (The code within /* and */ is not a comment, it is just the area of interest.  It is not commented in the actual .java file.)

Everytime I execute the code, it compiles, but does not pause for 1 second before continuing in the seconds >0 while loop.  

The first line of output comes from the main method in another class.  I see where my println statement is executed 24 times, so I know the loop is working, but I was expecting the timer.schedule to act as a pause.

Any help would be appreciated.  Please let me know if I need to further explain any part of the problms I am encountering.

Thanks,
Justin

-------------------------------------------------------------------------------
import java.util.*;
import java.lang.*;

public class Dispatcher {
  public static final int
      FCFS = 1,
      SJF  = 2,
      PS   = 3,
      RR   = 4;
  public static int quantom;
  private Timer timer;
  private int seconds;
  private int totalTime;
  private Job running;
  private Vector readyQ;
  private Vector allJobs;
  private int type;

  public Dispatcher(Vector allJobs, int type) {
    // The variable allJobs is holding all the jobs. This is not readyQ.
    // type is one of the above constant identifiers.

    int i = 0;
    timer = new Timer();
    totalTime = 0;
    int turnAroundTime = 0;
    int averageWaitingTime = 0;

    if(type == 2 || type == 3)
        allJobs = sort(allJobs, type);

    readyQ = new Vector(allJobs);
    //System.out.println("Size of readyQ = " + readyQ.size());

    while(!readyQ.isEmpty())
    {
        running = ((Job)allJobs.elementAt(i));
        seconds = running.burstTime;
        //System.out.println("Seconds = " + seconds);
        running.waitingTime = totalTime;
        averageWaitingTime += running.waitingTime;
        /*****************************************************************************
        while(seconds > 0)
        {
            System.out.println("I'm inside the seconds while-loop");
            timer.schedule(new RRTask(), 0, 1000);
            seconds--;
        } // terminates inner while loop
        *****************************************************************************/
        turnAroundTime += totalTime;
        System.out.println("i = " + i);
        readyQ.removeElementAt(i);
        allJobs.setElementAt((Job)running, i);
        i++;
    } // terminates outer while loop

    averageWaitingTime = averageWaitingTime/allJobs.size();
    System.out.println("Average waiting time in seconds = " + averageWaitingTime);

    turnAroundTime = turnAroundTime/allJobs.size();
    System.out.println("Average turnaround time in seconds = " + turnAroundTime);

    System.out.println("Total time used in seconds = " + totalTime);
    //timer.cancel();
  }

  class RRTask extends TimerTask {
    public void run() {
        totalTime++;

    }
  }

  private Vector sort(Vector v, int type){
    return allJobs;
  }
}

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
OUTPUT

Please wait for my answer.
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
i = 0
I'm inside the seconds while-loop
I'm inside the seconds while-loop
I'm inside the seconds while-loop
i = 1
I'm inside the seconds while-loop
I'm inside the seconds while-loopjava.lang.ArrayIndexOutOfBoundsException: 2 >= 1
      at java.util.Vector.removeElementAt(Vector.java:517)
      at Dispatcher.<init>(Dispatcher.java:50)
      at Main.main(Main.java:12)

I'm inside the seconds while-loop
i = 2
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
0
JPSimone
Asked:
JPSimone
  • 7
  • 6
  • 2
1 Solution
 
CEHJCommented:
What is your actual *objective* - is it this?

>> I need to execute the timer.schedule command X number of times without using the sleep command.
0
 
JPSimoneAuthor Commented:
Yes, I need to execute in "real-time".  So the execution of the while loop the first time should take 24 seconds, then three seconds, then three seconds again.
0
 
CEHJCommented:
OK - let me get this straight - you want to run a task for 24 seconds, then one for 3 and then another for 3?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
JPSimoneAuthor Commented:
Yes.  That is correct.
0
 
JPSimoneAuthor Commented:
But I cannot use timer.schedule(new RRTask(), 0, seconds*1000) because totalTime++ must be called from within the run() method of RRTask.
0
 
CEHJCommented:
I take it you mean each consecutively rather than concurrently? Synchronously or asynchronously with your main execution thread?
0
 
JPSimoneAuthor Commented:
Yes, they need to be executed consecutively rather than concurrently.
0
 
CEHJCommented:
I'll think about it awhile ;-)
0
 
InteractiveMindCommented:
I can't see why you don't want to use Thread#sleep(long) ?? This would be a lot easier, as you can just multithread it..
0
 
JPSimoneAuthor Commented:
One of the requirements is that the sleep function not be used.
0
 
CEHJCommented:
How about something like:


Thread twentyFour = new Thread(new FirstTaskRunnable()).start();
twentyFour.join(24000);
Thread threeOne = new Thread(new SecondTaskRunnable()).start();
threeOne.join(3000);
Thread threeTwo = new Thread(new ThirdTaskRunnable()).start();
threeTwo.join(3000);


?
0
 
InteractiveMindCommented:
Thanks to CEHJ's idea of using the Thread#join() method, I've come up with this:



import java.util.*;


public class ExampleOfUse
{
      public ExampleOfUse(){}
      
      public static void main( String [] args )
      {
            Process [] p = { new Process( 24 ) {
                                          public void run()
                                          {
                                                for(;;)
                                                {
                                                      System.out.println( "Task 1!" );
                                                }
                                          }
                                     },
                                     
                                     new Process( 3 ) {
                                           public void run()
                                           {
                                                 for(;;)
                                                {
                                                       System.out.println( "Task 2!" );
                                                 }
                                           }
                                     },
                                     
                                     new Process( 3 ) {
                                           public void run()
                                           {
                                                 for(;;)
                                                {
                                                       System.out.println( "Task 3!" );
                                                 }
                                           }
                                     }
                                    };
            Dispatcher d = new Dispatcher( p );
      }
}

class Dispatcher
{
      
      public Dispatcher( Process [] p )
      {
            if ( p.length > 0 )
            {      
                  for ( int i = 0; i < p.length; i++ )
                  {
                        p[i].begin();
                  }
            }
      }
      
}

class Process extends Thread
{
      private int secs;
      
      public Process( int secs )
      {
            this.secs = secs;
      }
      
      public void begin()
      {
            try
            {
                  start();
                  join( secs * 1000 );
                  stop();
            } catch ( Exception e ) {}
      }
      
      public void run() {}
}



You simple overide the run() method in the Process class, to do whatever you want, for example:

  Process myProcess = new Process( 3 )   // Pass the number of seconds to run for to the constructor.
  {
      public void run()
      {
           // Operation here.
      }
  };

Then you create an array of Process's, and pass it to the constructor of the Dispatch class .. have a play with it.

Regards;
0
 
CEHJCommented:
Of course that should have been

Thread twentyFour = new Thread(new FirstTaskRunnable());
twentyFour.start();

etc.
0
 
JPSimoneAuthor Commented:
Thank you both for your help.  Neither answer was exactly what I was looking for.  I have since figured out that by adding a:

 while(true){
   ;

it allowes for the the call to timer.schedule(...) to be run at the given interval while only executing the busy-waiting loop.

Again, thanks for your help and prompt responses.

JS
0
 
CEHJCommented:
:-)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now