title: Android run thread in service every X seconds
body: <p>I want to create a thread in an Android service that runs every X seconds</p>
  
  <p>I am currently using , but the postdelayed method seems to really lag out my app. </p>
  
  <pre><code>@Override
  public int onStartCommand(Intent intent, int flags, int startId){
  
      super.onStartCommand(intent, flags, startId);
  
      startRepeatingTask();
  
      return startId;
  }
  
  private final static int INTERVAL = 20000; //20 milliseconds
  Handler m_handler = new Handler();
  
  Runnable m_handlerTask = new Runnable()
  {
       @Override 
       public void run() {
           // this is bad
            m_handler.postDelayed(m_handlerTask, INTERVAL);
       }
  };
  
  void startRepeatingTask()
  {
      m_handlerTask.run(); 
  }
  
  void stopRepeatingTask()
  {
     m_handler.removeCallbacks(m_handlerTask);
     stopSelf();
  }
  </code></pre>
  
  <p>I want to do a new thread like this:</p>
  
  <pre><code>public void threadRun()
  {
      Thread triggerService = new Thread(new Runnable(){
          public void run(){
              Looper.prepare();
              try{
                      //do stuff here?
  
              }catch(Exception ex){
                      System.out.println("Exception in triggerService Thread -- "+ex);
              }//end catch
  
  
          }//end run
      }, "aThread");
      triggerService.start();      
  
      //perhaps do stuff here with a timer?
      timer1=new Timer();
  
      timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL);
  }
  </code></pre>
  
  <p>I'm not sure the best way to do a background thread to run at a certain interval, insight appreciated!</p>