CoolGuy47
CoolGuy47

Reputation: 3

Is there a way to make the java timer fire a certain number of times, then stop?

Ok, so I need a timer to fire X number of times, ie. 5 times, and I know how to make it all work, but I can't figure out this one problem. If there isn't just some invoked method, then maybe there's a different way to do something like that? but here's the code i'm working with;

int delay = 5000;
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    //some action here
  }
};

new Timer(delay, taskPerformer).start();

(also, if theres anything wrong with this code, please tell me. Thanks!)

Upvotes: 0

Views: 842

Answers (1)

elias-berg
elias-berg

Reputation: 559

Something like this?

Timer t;
int firecount = 0;    

int delay = 5000;
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {        
    // action code
    firecount++;

    if ( firecount == 5 )
      t.stop();
};

t = new Timer(delay, taskPerformer).start();

Upvotes: 3

Related Questions