I am using WorkManager to schedule my worker for data sync with an online service. I am using a periodic worker for that.
fun schedule(context: Context, policy: ExistingPeriodicWorkPolicy = ExistingPeriodicWorkPolicy.KEEP)
{
val request = PeriodicWorkRequestBuilder<MissingPublishWorker>(15, TimeUnit.MINUTES)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(TAG_PUBLISH_WORKER, policy, request)
}
This worker checks the pending sync data on the database and sends them to an online service. Checking happens every 15 minutes (minimum possible time)
How can I schedule this such that the worker sends pending sync data as soon as they are created and not wait 15 minutes cycles?.
Something like how WhatsApp sends sms
CodePudding user response:
I think your job does not need an immediate worker. you can schedule it to do that when os wants. but if you want to run it immediately you should use "oneTimeWorkRequest".when you want run worker without delay schedule that with "oneTimeWorkRequest" and when need run that periodically schedule it with "PeriodicWorkRequest".
CodePudding user response:
Messaging apps use the persistent connection between the client (Android App) and Messaging server ex: WebSockets.
Periodic WorkRequest is not suitable for your use-case since WorkManager respects system resources and is a solution for deferred background tasks. So, if it's a messaging application in your case; you can use WebSockets or some similar solution, not REST APIs.
Otherwise, if you want to send individual messages then use WorkManager OneTimeRequest with setting setExpedited(true)
see Reference.