title: Using single Timer vs multiple Timers for scheduling TimerTasks in Android
body: <p>I think I don't fully understand how the <em>Timer</em> and <em>TimerTask</em> work in Java and Android. Now, I have a number of periodic tasks defined, to be scheduled within a timer.</p>
  
  <p>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?</p>
  
  <p>What is the differences between these approaches?</p>
  
  <p>Sample code for <strong>approach 1:</strong></p>
  
  <pre><code>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
      }
  }
  </code></pre>
  
  <p>Sample code for <strong>approach 2:</strong></p>
  
  <pre><code>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);
      }
  }
  </code></pre>