Job Scheduler vs Background Service

jobscheduler
jobscheduler vs workmanager
job scheduler documentation
jobscheduler vs jobintentservice
start job service android
firebase job dispatcher vs job scheduler
jobscheduler java
android run task at specific time

I have an app which has a feature A which should run in background every minute. Feature A is that the app should connect to a database, read some data then get the current location of the device and based on them check a condition, if the condition is true it should send a statusbar notification to the user so that when the user clicks on the notification the UI of the app will be displayed and something happens. This background task should run permanently every minute, regardless the app is used, closed, terminated (like facebook or Whatsapp that show us notifications regardless they are in the app stack or not). Now I have searched and have found that Android offers Job Scheduler,Background Service, AlarmManager and Handlers. But the more I read about them the more contradictory the statements appear to me.

  1. About Handlers I have read that they do not exist for long delays and will be terminated after system reboot. So they won't be appropriate for my task.
  2. But AlarmManager seems to be a good candidate for the problem because when permitted they exist even after system reboot and can rerun the app. But in the Android Documentation that the Alarm Manager is intended to be used for tasks that have to be run at a specific time (like the Alarm Clock). But my task has to be run every minute.
  3. Then there is Background Service. This is more for tasks like downloading in the background as I have read and not intended for doing something I have explained.
  4. JobScheduler seems not to be for a task that has to be done in permanently, but for tasks that fulfill a specific constraint like idle, or no network... So which of these (or other ones if they exist) do you recommend to use for the task I explained in the first part

I have an app which has a feature A which should run in background every minute.

That will not happen on hundreds of millions of Android devices, those running Android 6.0 and higher, due to Doze mode (and, possibly, app standby, depending on the rest of your app).

But AlarmManager seems to be a good candidate for the problem because when permitted they exist even after system reboot

No, they do not. You need to reschedule all alarms scheduled with AlarmManager after a reboot.

the Alarm Manager is intended to be used for tasks that have to be run at a specific time

AlarmManager supports repeating options.

This is more for tasks like downloading in the background as I have read and not intended for doing something I have explained.

A Service will be essential for whatever solution you wind up using.

JobScheduler seems not to be for a task that has to be done in permanently, but for tasks that fulfill a specific constraint like idle, or no network

JobScheduler, as with AlarmManager, supports repeating jobs.

So which of these (or other ones if they exist) do you recommend to use for the task I explained in the first part

Use none of them, as you cannot run things every minute on Android 6.0+ once the device goes into Doze mode, which will be within an hour of the screen turning off. Instead, either redesign the app to only need background work a few times per day, or do not bother writing the app.

Choosing the Right Background Scheduler in Android, The AlarmManager provides access to system-level alarm services. JobScheduler helps perform background work in an efficient way,  Then there is Background Service. This is more for tasks like downloading in the background as I have read and not intended for doing something I have explained. JobScheduler seems not to be for a task that has to be done in permanently, but for tasks that fulfill a specific constraint like idle, or no network

You can use modern JobScheduler API which was introduced in Android 5.0 if your minSdkVersion=21.

Also there is https://github.com/firebase/firebase-jobdispatcher-android which requires installed Google Play minSdkVersion=9

But I recommend to use this library https://github.com/evernote/android-job where depending on the Android version either the JobScheduler, GcmNetworkManager or AlarmManager will be used.

With these APIs you can schedule your job and run service which describes task.

UPDATE Now it is better to use new WorkManager (docs). android-job will be deprecated soon

Replacing Services With JobScheduler in Android Oreo 8.0 , Android Framework JobScheduler addresses new background execution limitations for Xamarin.Android apps targeting Android 5.0 (API level  Job Scheduler JobScheduler helps perform background work in an efficient way, especially networking. JobServices are scheduled to run based on criteria declared in JobInfo.Builder (). These criteria include performing the JobService only when the device is charging, idle, connected to a network or connected to an unmetered network.

First, a JobService is a Service. A background service is ambiguous, let me guess you mean a service that runs in the background thread. Job Service runs on the ui thread but you can create an async task object within it to make it run in the background.

From your question, JobService is not the way to go.What i suggest is:

  1. You can create a class that extends IntentService (this runs on the background thread) in the onDestroy method of that class, send a broadcast and make the broadcast restart the service.

     @onDestroy(){
     Intent broadcastIntent = new 
     Intent("com.example.myapp.serviceRestarted");
     sendBroadcast(broadcastIntent);}
    
  2. Create a class that extends broadcast reciever

     public class RestartServiceReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {
     context.startService(new Intent(context, 
     MyService.class));
    } 
    }
    
    1. In your manifest, register your service and reciever
<receiver
            android:name=".RestartServiceReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.myapp.serviceRestarted" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

The boot permision is to enable the reciever be called the the system has finished booting, and once the reciever is called, the service will be called again.

Guide to background processing, Job scheduler is the Android Framework API for scheduling Background tasks or services. It was introduced by Google in API 21. So we don't want to care much about how it is scheduling the service. The main thing here is It is working based on robust conditions like network availability, device charging state and so on. If you have a Windows service or want to use the Windows Task Scheduler, it is common to host your background tasks within a dedicated virtual machine. Azure Batch . Batch is a platform service that schedules compute-intensive work to run on a managed collection of virtual machines.

According to this and other link in comment 1 below

You should use AlarmManager for your task.

If you need to set alarms that fire while in Doze, use:

 setAndAllowWhileIdle() or setExactAndAllowWhileIdle().

For a full easy to understand explanation for the different ways to do stuff in the background read: https://www.bignerdranch.com/blog/choosing-the-right-background-scheduler-in-android/

Good Luck!

Job Scheduler -An Overview - IVYMobility TechBytes, whenever the user brings the main activity to the foreground, until the main activity goes in the background. How. A plain old service hosts a timer that repeats a  One of those features is a task scheduler that is configured 100% by code. By leveraging Coravel's ease-of-use with the simplicity of .NET Core's worker service project template, I'll show you how easily and quickly you can build a small back-end console application that will run your scheduled background jobs! Worker Service Template

In the previous versions of Android, people used Handler or background services for this purpose. After a while, they announced alarm manager class for permanent, scheduled works.

Whatsapp, facebook or some social media applications mostly use google cloud messaging for the notification purpose which is not useful for you.

I will recommend you to use Alarm manager for this. After the KitKat version(4.2), Operating System blocks the background handler for better use of battery.

Background services are mostly used for image upload or some heavy process which has an ending time. When you are sending a video to your friend on Whatsapp, background process starts and uploads the video to backend server. I am not sure about JobScheduler api for supporting the older versions of support, but it is as good as Alarm Manager.

Oreo and service vs jobscheduler : androiddev, Does your Android application needs to run a background job repeatedly every This tutorial shows you how to schedule a background job using JobScheduler The service must be registered in AndroidManifest.xml . JobScheduler: A system service that will run jobs scheduled by apps. JobService: A class extended by applications and contains the code that runs as part of a job. The code for each job is contained in a class that extends the JobService class and requests the android.permission.BIND_JOB_SERVICE permission.

Android, Options for scheduling. If you have a repetitive task in your Android app, you need to consider that activities and services can be terminated by the  Consuming a scoped service in a background task. To use scoped services within a BackgroundService, create a scope. No scope is created for a hosted service by default. The scoped background task service contains the background task's logic. In the following example: The service is asynchronous. The DoWork method returns a Task.

Scheduling of tasks with the Android JobScheduler, Android Background Processing Part 2: JobScheduler and WorkManager moving on to scheduling work, and finishing up with Services. Processing data in the background is an important part of creating an Android application that is both responsive for your users as well as a good citizen on the Android platform. This guide defines background task categories, provides you with criteria to categorize your tasks, and recommends APIs that you should use to execute them.

Android Background Processing Part 2: JobScheduler and , Scheduler specifies when to run jobs, keeps a history of job results that you can review, and then predictably and reliably schedules workloads to run. Other Azure scheduling capabilities also use Scheduler in the background, for example, Azure WebJobs , which is a Web Apps feature in Azure App Service.

Comments
  • You told that you need to fetch some data from a database and then check a condition. The best way to do it is pushing the information from the server.
  • (...) The best way to do it is pushing the data from the server using GCM. But it requires a server improvement (maybe you can't make changes on the server). ( I know that it was not the question, but It maybe help who started in an wrong way looking for an app update.).
  • @ErickM.Sprengel are server pushes reliably delivered? via say Firebase Messaging (previously GCM)
  • So I can run the task every minute and it will stop when in doze mode. But after leaving the doze mode the task will run again, isn't it?
  • @MoProg: Correct. However, devices are in Doze mode a lot of the time. That is particularly true on Android 7.0, where they added a "partial Doze mode" that kicks in immediately after the screen goes off.
  • @MoProg: If you are referring to Facebook and WhatsApp, they use Firebase Cloud Messaging, most likely. That is for a server pushing messages down to a device, for when data changes of relevance on the server. FCM messages are allowed to temporarily allow an app to do some work, even in Doze mode. If by "connect to a database", you mean that your app is polling some Web service, you could switch to a push model, using FCM, rather than trying to do something every minute on your device.
  • @CordRehn: Note that Google had been banning apps that do what you describe ("take them to the settings page to disable the 'Battery Optimizations' setting for your app"). AFAIK, the closest that you can get safely is ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, which takes them to the list.
  • @user2297550: "Does the reliability and instant-ness of Facebook & WhatsApp come automatically for free with FCM?" -- I would use FCM for opportunistic delivery, with periodic (unreliable) polling as a backup. "is it right to infer that FCM has a special status in Android+Google that other messaging providers can never have?" -- if by "Android+Google" you mean "Google Play ecosystem", then the big advantage that Google has is that their stuff is pre-installed, pre-added to the battery optimization whitelist, and can't be banned by Google.
  • Damn, they deprecate their APIs faster than they can update their docs. I am spending so much time running behind what the heck I should use now for some sort of background processing. Service? No! AlarmManager? No. AsyncTask? ThreadPool, Bound Service? BroadcastReceiver? JobScheduler? Firebase JobScheduler? WorkManager? FCM? Currently all the docs say use Firebase-JobScheduler. Now it is already WorkManager that might use Firebase or JobScheduler. Gosh.
  • Link 2 :developer.android.com/topic/performance/scheduling.html
  • Recommend the BigNedRanch link above, it covers it very well. Basically use JobScheduler and forget about API < 21 which is 10% of market and falling. Though wondering why the article doesn't mention Service class ?
  • my service works on other versions i'm already have this broadcast I said the issue that stops my service to start is this system warning permission
  • In higher android devices, above API 5 or 6, the device will enter doze state frequently if the user is not interacting with the app(and the app is in background) and the android system will kill the background service.
  • One point to @Code Pope is that according to the docs developer.android.com/training/monitoring-device-state/… the device goes into Doze mode when the screen is off, the device unplugged and - this is the interesting thing for your app - the device is stationary. According to this, although the device may go into Doze mode, it may not matter to you since the location will not have changed (and therefore the notification may not be needed). If on the other hand, the changes in the database alone are capable of triggering the notification, then this would not work.
  • I request for a fair explanation before getting a down-vote, because it does exactly what the OP asked for: perform an action every minute, even when the app is killed.