Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters to Timer Task (Java)

Tags:

java

timer

I have a timer task in a loop. I want to pass into the time task which number it is in a loop.

Is that possible?

My code:

...
int i = 0;
while (i < array.size){
    Timer timer = new Timer();
    timer.schedule(new RegrowCornAnimate(), 0, 1000);
i++
}
...

class RegrowCornAnimate extends TimerTask {
     public void run() {
//Do stuff
   }
}

How can I change it so I can use i in the TimerTask class? -as in each TimerTask will know which i it was created under/in/from.

like image 710
James Andrew Avatar asked Dec 14 '11 01:12

James Andrew


2 Answers

class RegrowCornAnimate extends TimerTask {

    private final int serial;


    RegrowCornAnimate ( int serial )
    {
      this.serial = serial;
    }

    public void run() {
      //Do stuff
    }
}

...
int i = 0;
while (i < array.size){
    Timer timer = new Timer();
    timer.schedule(new RegrowCornAnimate( i ), 0, 1000);
    i++;
}
...
like image 178
Alexander Pogrebnyak Avatar answered Oct 13 '22 23:10

Alexander Pogrebnyak


Give the RegrowCornAnimate class a constructor that takes an int and store that in a field. Pass i to the constructor when you create it.

like image 22
ColinD Avatar answered Oct 14 '22 01:10

ColinD