I think I don't fully understand how the Timer and TimerTask work in Java and Android. Now, I have a number of periodic tasks defined, to be scheduled within a timer.
I wonder should I use a single timer to schedule tasks, or using different timer instances for each task is ok? Do timers have their own threads? Do scheduled tasks executed in new threads? What is happening in the background?
What is the differences between these approaches?
Sample code for approach 1:
private void initTasks() {
TimerTask task1 = new MyTimerTask1();
TimerTask task2 = new MyTimerTask2();
TimerTask task3 = new MyTimerTask3();
Timer timer = new Timer();
timer.schedule(task1, 0, TASK1_PERIOD);
timer.schedule(task2, 0, TASK2_PERIOD);
timer.schedule(task3, 0, TASK3_PERIOD);
}
class MyTimerTask1 extends TimerTask {
public void run() {
//do task1
}
}
class MyTimerTask2 extends TimerTask {
public void run() {
//do task2
}
}
class MyTimerTask3 extends TimerTask {
public void run() {
//do task3
}
}
Sample code for approach 2:
private void initTasks() {
MyTimerTask1 task1 = new MyTimerTask1();
MyTimerTask2 task2 = new MyTimerTask2();
MyTimerTask3 task3 = new MyTimerTask3();
task1.start();
task2.start();
task3.start();
}
class MyTimerTask1 extends TimerTask {
private Timer timer;
public void run() {
//do task1
}
public void start() {
timer = new Timer();
timer.schedule(this, 0, TASK1_PERIOD);
}
}
class MyTimerTask2 extends TimerTask {
private Timer timer;
public void run() {
//do task2
}
public void start() {
timer = new Timer();
timer.schedule(this, 0, TASK2_PERIOD);
}
}
class MyTimerTask3 extends TimerTask {
private Timer timer;
public void run() {
//do task3
}
public void start() {
timer = new Timer();
timer.schedule(this, 0, TASK3_PERIOD);
}
}