title: Scheduling a task using ScheduledExecutorService with newSingleThreadScheduledExecutor in Service resulting in task running in multiple threads
body: <p>In my Android app I scheduled a task by starting a service, in my <code>MyActivity</code>:</p>
  <pre><code>@Override
  protected void onResume() {
     super.onResume();
  
     synchronized (this) {
        if (!serviceDidStart) {
           serviceDidStart = true;
           Intent intent = new Intent(this, CustomService.class);
           startService(intent);
     }
  }
  
  @Override
  protected void onPause() {
     super.onPause();
  
     Intent intent = new Intent(this, CustomService.class);
     stopService(intent);
     serviceDidStart = false;
  }
  </code></pre>
  <p>And then in my <code>CustomService</code>:</p>
  <pre><code>private ScheduledExecutorService scheduler;
  private scheduled = false;
  private Runnable repeatingTask = new Runnable() {
     @Override
     public void run() {
        System.out.println(&quot;Thread: &quot; + Thread.currentThread().getId());
     }
  };
  
  @Override
  public void onCreate() {
     scheduler = Executors.newSingleThreadScheduledExecutor();
  }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
  
     if (!scheduled) {
        scheduler.scheduleWithFixedDelay(repeatingTask, 0, 5, TimeUnit.SECONDS);
        scheduled = true;
     }
  
      return Service.START_STICKY;
  }
  </code></pre>
  <p>I expect that the task is only scheduled and executed in one single thread, which should result in output like the following:</p>
  <blockquote>
  <p>Thread: 350</p>
  <p>Thread: 350</p>
  <p>Thread: 350</p>
  </blockquote>
  <p>It is fine and working as I expected if I don't do anything else after launch. However, if I press home button, and then resume my app, the output and the task scheduling become a mess like the following:</p>
  <blockquote>
  <p>Thread: 350</p>
  <p>Thread: 362</p>
  <p>Thread: 367</p>
  <p>Thread: 350</p>
  <p>Thread: 362</p>
  <p>Thread: 367</p>
  </blockquote>
  <p>Did I do something wrong? What should I do instead if I would like to schedule and execute the repeatingTask in only one thread through the lifespan of the app (i.e. only using one thread for scheduling and executing the task even after I pause and resume into the activity)?</p>
  <p>I am quite new to Android and Java development and I have no idea what is going wrong in my case. Any help and guidance would be great, thanks!</p>
  <p><strong>Update and edit:</strong></p>
  <ul>
  <li>add back <code>serviceDidStart = false;</code> in <code>MyActivity</code>'s <code>onPause()</code></li>
  </ul>