问题
I have been checking with the other links, stackoverflow to reduce time period of Work manager, but I found below link
How to reduce time of PeriodicWorkManager in WorkManager
Above link says that minimum time is 15 minutes.
Need to send data instantly from mobile to server. Is there any alternative for reducing the time period ?
Please help me on this.Thanks in Advance.
回答1:
In the work manager
, there is a minimum time interval between two periodic requests is 15 minutes
.
Read this doc: https://developer.android.com/reference/kotlin/androidx/work/PeriodicWorkRequest
you can not reduce it in the work manager
.
if you want to reduce time in that case you need to use JobScheduler
it gives options with specific time intervals to execute your request.
https://developer.android.com/reference/android/app/job/JobScheduler
回答2:
If you need to send instantly, you can try OneTimeWorkRequest
.
Though its execution will also be dependent on the constraints you add or some other cases, but it'll start right after you call it most of the times.
Docs, Refer
Edit:
And then if you want this periodically
, You can create a PeriodicWorkRequest
and start your OneTimeWorkRequest
in it.
eg. Let's say you're having 2 methods,
startOneTimeWorker()
, startPeriodicWorker()
If you want to sync it once and instantly OneTimeWorker
will do the job.
But if you want to sync instantly and then schedule it also, call startOneTimeWorker()
, and then startPeriodicWorker()
. Where Periodic worker will be calling startOneTimeWorker()
in it's doWork()
So for the first time, OneTimeWorkRequest
will be called instantly and then it'll be called according to the schedule of PeriodicTimeWorkRequest
.
- Call
OneTimeWorkRequest
- Schedule
PeriodicWorkRequest
, callingOneTimeWorkRequest
in it
回答3:
You can make your Worker
with OneTimeWorkRequest
, and just before the closing (read returning) of it's dowWork()
, make it register itself again.
That will go like:
val tenMinuteRequest = OneTimeWorkRequestBuilder<YourWorker>()
.setInitialDelay(10, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(applicationContext)
.enqueue(tenMinuteRequest)
//return Result.Success here or whatever
When you fire this Worker from another class, it will do
its work
and reschedules itself right after, and here goes the cycle.
回答4:
If you want to send Data instantly from Mobile to Server one time then use OneTimeWorkRequestBuilder , otherwise use ForeGround Service instead of WorkManager for sending continuous data upload to server.
Both of these strategy will ensure the data upload at server side. And if it is heavy upload work which may take longer than 10 minutes , please use ForeGround Service definitely.
来源:https://stackoverflow.com/questions/61811294/how-to-decrease-time-period-of-workmanager-android