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
@Higor is using the java.util.Timer timer ?
– Erick Gallani
@Higor see my issue in reply
– Erick Gallani
I was using java.swing.Timer Timer, switched and managed to use here. Thanks, hugs.
– Higor
@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.
– Erick Gallani