title: Reusing timer in android
body: <p>In my android app, I have the following relevant piece of code:</p>
  
  <pre><code>/*Code outside*/    
  button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          Timer t = new Timer();
          t.scheduleAtFixedRate(
              new TimerTask(){
                  public void run(){
                      stuffToBeDone();
                  }
              },someVariableDelay,someVariablePeriod);
      }
  }
  </code></pre>
  
  <p>Everything was going fine until I noticed that <em>stuffToBeDone()</em> was running once for every time I pressed the button. As far as I understand, every time <em>onClick()</em> is called and the old Timer should not exist anymore, but somehow the TimerTask survives. </p>
  
  <p>In the second button click, I no longer have a reference to the first Timer to <em>cancel()</em> it (because it should not exist anymore). And if I declare the Timer as a <em>final</em> variable in the <em>Code outside</em> so that I can do it, after canceling I cannot reuse it anymore. So how can I terminate that TimerTask but then still be able to use a Timer?</p>