Reputation: 62439
I have created WorkRequest on WorkManager. I just used first time.
I am stuck to update Repeat Interval when server sends me new interval.
Is this possible to update WorkRequest's Interval runtime when its changed on server side.
I have tried as follow:
My code is:
public static void startLocationTracker() {
/**
* Getting Default Minutes from General Params
*/
List<GeneralParamMaster> generalParamMasters = CommonUses.getGeneralSettings();
int repeatInterval = 0;
if (generalParamMasters.size() > 0) {
repeatInterval = TextUtils.isEmpty(generalParamMasters.get(0).getAutoLatLongTime()) ? DEFAULT_LOCATION_UPDATE_TIME : Integer.parseInt(generalParamMasters.get(0).getAutoLatLongTime());
}
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, repeatInterval, TimeUnit.MINUTES)
.addTag("Location")
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);
}
My Question/Confusion is::
Your help would be appreciated.
Upvotes: 1
Views: 1606
Reputation: 945
I posted solution to similar queston here.
The point is to keep your interval in sharedPrefs, and check if it is changed, and based on that condition, to use KEEP or REPLACE policy.
Upvotes: 0
Reputation: 563
pfmaggi already answered this above; if you call this method a second time, it will replace your original WorkRequest.
You can update your interval by calling the same method that you have and use ExistingWorkPolicy.REPLACE with a different length of time.
Upvotes: 0
Reputation: 6496
This works because you're enqueueing a new WorkRequest
as a Unique periodic work, replacing whatever was the previour WorkRequest
and its Interval.
Keep in mind that it may happens that you replace a PeriodWorker while it is running, because you're using ExistingPeriodicWorkPolicy.REPLACE
. If another worker, associated to the same UniqueName
, it's running while you call enqueueUniquePeriodicWork
, the Worker will be cancelled and the new one will be scheduled.
For this reason it's important to handle the cancellation correctly in your Worker
class, as explained in the documentation.
Upvotes: 1