title: Scheduling recurring task in Android
body: <p>I'm designing an app that has a recurring task of sending presence to a dedicated server as long as the app is in foreground.</p>
  
  <p>In my searches across the web I saw a few different approaches and wanted to know what is the best way of doing this.</p>
  
  <p><strong>What is the best way to schedule a server call?</strong></p>
  
  <p>The options I saw were:</p>
  
  <ol>
  <li><p><a href="http://developer.android.com/reference/java/util/Timer.html" rel="noreferrer">Timer </a>.</p></li>
  <li><p><a href="http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html" rel="noreferrer">ScheduledThreadPoolExecutor</a>.</p></li>
  <li><p><a href="http://developer.android.com/reference/android/app/Service.html" rel="noreferrer">Service</a>.</p></li>
  <li><p>BroadcastReciever with <a href="http://developer.android.com/reference/android/app/AlarmManager.html" rel="noreferrer">AlarmManager</a>.</p></li>
  </ol>
  
  <p>What's your opinion?</p>
  
  <p><strong>EDIT:</strong>  <br/>The reason I need this is for a chat based app that sends all the user actions to a remote server. <br/>i.e. user is typing a message, user is reading a message, user is online, user is offline etc.</p>
  
  <p>This means that once every interval, I need to send the server what I'm doing, since I open a chat room with other people, they need to know what I'm doing.</p>
  
  <p>Similar to the whatsapp message feedback mechanism:
  <img src="https://i.stack.imgur.com/xU5Ki.png" alt="message looks delivered"></p>
  
  <p><strong>EDIT #2:</strong>  <br/>
  Recurring tasks should now be scheduled almost always via the <code>JobScheduler</code> API (or <a href="https://github.com/firebase/firebase-jobdispatcher-android" rel="noreferrer"><code>FirebaseJobDispatcher</code></a> for lower APIs) in order to prevent battery draining issues as can be read in the <a href="https://developer.android.com/topic/performance/vitals/wakeup.html" rel="noreferrer">vitals section</a> of the Android training</p>
  
  <p><strong>EDIT #3:</strong>  <br/>
  FirebaseJobDispatcher has been deprecated and replaced by <a href="https://developer.android.com/topic/libraries/architecture/workmanager" rel="noreferrer">Workmanager</a>, which also incorporates features of JobScheduler. </p>