Pause program with Timer

1

I need to use it to wait 2 minutes before running a method. I already researched and can not find anything clear enough to help me.

I've already used Thread.sleep() plus it locks the whole thread , and that's not what I'm looking for. Thanks to all who help.

    
asked by anonymous 16.09.2015 / 18:52

1 answer

3

This 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
    }
}

Dai you call the execute by passing 120 seconds to the method.

OBS: This example uses the java.util.Timer timer link

If you are going to use the javax.swing.Timer doc: link

So you should 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
    
16.09.2015 / 19:03