Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are differences between BackoffPolicy.EXPONENTIAL and BackoffPolicy.LINEAR when working with Work Manager?

There is no any official doc (as I have read the docs at least) that explain the usage and the mechanism behind these two modes . How do they work ? And what problem do they solve ?

I will appreciate that if anyone can simplified it for me , because I have tested both and have not seen any interesting thing . If you ask me , I would say that OneTimeWorkRequest.setBackoffCriteria() does not affect to the work .

Here are my codes ,

@Override
public void doSomethingUseful(String order) {

    Constraints constraint = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();

    Data data = new Data.Builder()
            .putString("order", order)
            .build();

    OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(OrderSenderWorker.class)
            .setConstraints(constraint)
            .setInputData(data)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15, TimeUnit.SECONDS)
            .build();

    WorkManager.getInstance().beginUniqueWork("refresh-order", ExistingWorkPolicy.REPLACE, oneTimeWorkRequest).enqueue();

}

And in Worker class whenever I get something wrong , I do return WorkerResult.RETRY in doWork() method.

Thanks in advance .

like image 564
Mehdi Jahed Manesh Avatar asked Sep 25 '18 10:09

Mehdi Jahed Manesh


2 Answers

Taking into account that the WorkManager uses the run attempt count as reference, for a BackoffPolicy of 15 seconds, will be as next:

  • For linear: work start time + (15 * run attempt count)

  • For exponential: work start time + Math.scalb(15, run attempt count - 1)

The work start time, is when the work was first executed (the 1st run attempt).

Run attempt count is how many times the WorkManager has tried to execute an specific Work.

Also note that the maximum delay will be capped at WorkRequest.MAX_BACKOFF_MILLIS.

Take into consideration that a retry will only happen if you specify that the Work requires it by returning WorkerResult.RETRY

like image 164
PerracoLabs Avatar answered Nov 15 '22 19:11

PerracoLabs


Consider if you are hitting an API on server if server return specific status you hit the API again after some amount of time.

Now to control the interval time between any two API call, you can use BackoffPolicy.

If you use BackoffPolicy.LINEAR then the interval time will be increased linearly until the threshold reached.

or if you use BackoffPolicy.EXPONENTIAL then the interval time will be increased exponential until the threshold reached.

like image 32
thegoodguy Avatar answered Nov 15 '22 21:11

thegoodguy