You are on page 1of 2

Sintaxe:

int delay = 5000; // tempo de espera antes da 1ª execução da tarefa.


int interval = 1000; // intervalo no qual a tarefa será executada.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Olá World!");
}
}, delay, interval);

Exemplo:

Timer timer1 = new Timer();


Timer timer2 = new Timer();

public void Tarefa1(){


int delay = 2000; // delay de 2 seg.
int interval = 5000; // intervalo de 1 seg.

timer1.scheduleAtFixedRate(new TimerTask() {
public void run() {
JOptionPane.showMessageDialog(null, "Executei a Tarefa 1");
}
}, delay, interval);
}

public void Tarefa2()


{
int delay = 0; // delay de 0 seg.
int interval = 2000; // intervalo de 2 seg.

timer2.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Olá World no console");
}
}, delay, interval);
}

Parar tarefas:

public void PararTarefas(){


// Encerra as tarefas
timer1.cancel();
timer2.cancel();
}

---------------------------------------------------

import java.util.Timer;
import java.util.TimerTask;

public class Reminder {


Timer timer;

public Reminder(int seconds) {


timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}

public static void main(String args[]) {


new Reminder(5);
System.out.println("Task scheduled.");
}
}
Quando você rodar o exemplo, vai ver:
Task scheduled.
(depois de 5 segundos)
Time's up!

-----------------------------------------------

You might also like