Pause program with Timer

Asked

Viewed 477 times

1

I need to use it to wait 2 minutes before executing a method. I have researched and can’t find anything clear enough to help me.

I’ve used the Thread.sleep() the more he locks the thread all of it, and that’s not what I’m after. Thank you to those who help.

1 answer

3

That should be simple.

Timer timer;

public Executar(int segundos) {
    timer = new Timer();
    timer.schedule(new MinhaFuncao(), segundos*1000);
}

class MinhaFuncao extends TimerTask {
    public void run() {
        //faz tudo que precisa fazer aqui
        timer.cancel(); //Termina a task
    }
}

Hence you call the run by passing 120 seconds to the method.

OBS: this example uses the java.util.Timer timer http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

If you are going to use javax.swing.Timer doc: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Then you must do so

Timer timer;

int delay = 120*1000; //2 minutos

ActionListener tarefaAgendada = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //faz o que tem que fazer
    }
};

timer = new Timer(delay, taskPerformer);
timer.setRepeats(false); //faz rodar apenas 1 vez, sem isso ele ficar invocando a action de 2 em 2 minutos
timer.start(); //inicia a task
  • The timer constructor asks for 2 parameters here. An integer and an Actionlistener. Hence the code did not even run.

  • @Higor is using the java.util.Timer timer ?

  • @Higor see my issue in reply

  • I was using java.swing.Timer Timer, switched and managed to use here. Thanks, hugs.

  • 1

    @I’m glad you solved your problem. Remember to mark the answer as correct to help other users who might have the same question as you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.