Jump to content

Timer


mpeixoto

Recommended Posts

Cria uma classe que extenda java.util.TimerTask

Do género:

import java.util.TimerTask;
class Tarefa extends TimerTask
{
  int segundos;
  public void run()
  {
     // escreves aqui o código que vai correr em cada intervalo do timer
     System.out.println(++segundos); // Vai contando os segundos que passam
  }
}

Depois para correres o Timer fazes por ex.:

import java.util.Timer;
class Teste
{
  public static void main(String[] args)
  {
     Timer timer=new Timer();
     timer.schedule(new Tarefa(),1000,1000); // Começa a executar o timer de acordo com a TimerTask
                                             // definida na classe Tarefa, dentro de 1000ms (1seg) e
                                             // repete a cada 1000ms (todos os segundos subsequentes)
     // Para paráres o timer cria uma condição que chame o método timer.cancel();
  }
}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.