androidfirebase-job-dispatcher

Firebase Job Dispatcher


I'm creating an application which needs to send a request to an API. This request has to be send every 2 minutes. To do this I'm using Firebase Job Dispatcher

The problem is that the first request is send at time but the next ones are sent with a greater delay: eg.

As you can imagine, after a day, the delay will be 30 minutes or even more...

here is the code I used to create the job (in main activity - onCreate)

        Job pingJob = mDispatcher.newJobBuilder()
            .setService(PingJob.class) // the job class to execute
            .setTag(PingJob.TAG) //tag - name of the job
            .setRecurring(true) // repeat
            .setTrigger(Trigger.executionWindow(60, 60*2))
            .setReplaceCurrent(false)
            .build();

    mDispatcher.mustSchedule(pingJob);

Here is the PingJob class (to be sure the issue wasn't what i was doing in onStartJob, I only put a log):

public class PingJob extends Job {
    public static final String TAG = "ping_job";

    @Override
    public boolean onStartJob(final JobParameters params) {
        Log.d("ping job", "just put a log to see when is executed");
        jobFinished(params, true);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

}

I'm using an Android box with Android 6.0.1 (but my application has to run on 4.3 device too that why I'm using firebase instead of JobScheduler) and Google Play services 11.5.09 (434).

Do you have any ideas why it's doing this ? and if there is a way to get around this problem ? if not, is there a other way to do a job every 2 minutes ?


Solution

  • You're doing nothing wrong. This is a designed expected behaviour. FirebaseJobDispatcher uses a scheduling engine inside Google Play Services which likely to use JobScheduler under the hood for Android 5.0 and higher. JobScheduler batches tasks from different apps into one batch to not wake up a device too often and save a battery. So there's no guarantee that your task will be executed exactly every 2 minutes. If you need this precision consider using AlarmManager which is not recommended for doing any network calls as it affects a battery life.

    Why do you even need to send a request such often? Consider to think more about what you're doing. It might be better to save the data you're sending to the backend in a database or on a disk. Then you can send it in batches every 30-60 minutes or whatever works for you. You can also use Firebase Cloud Messaging to send a message to a device to ask it to send the data to the backend when it's needed.