Android WorkManager Periodic Work — Complete Guide
In this tutorial, you'll learn about Android WorkManager Periodic Work. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your periodic worker runs every 5 minutes (but the minimum is 15), or it starts a new execution before the previous one finishes, or it stops running after a few cycles.
Wrong Approach ❌
// 5-minute interval — below minimum!
val request = PeriodicWorkRequestBuilder<SyncWorker>(5, TimeUnit.MINUTES)
.build()
Output: WorkManager ignores the 5-minute request and uses 15 minutes as the effective minimum. The worker runs unexpectedly infrequently.
Right Approach ✅
// Minimum interval is 15 minutes
val request = PeriodicWorkRequestBuilder<SyncWorker>(
15, TimeUnit.MINUTES
).apply {
setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
// Add a flex interval for timing flexibility
setFlexTime(5, TimeUnit.MINUTES)
}.build()
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(
"sync_worker",
ExistingPeriodicWorkPolicy.KEEP,
request
)
Output: Worker runs every 15-20 minutes (within flex window), respecting constraints.
Prevention
- Minimum interval is 15 minutes — never set lower.
- Use
setFlexTimeto define a window within which the work can run. - Use
enqueueUniquePeriodicWorkto prevent duplicate schedules. - The actual interval may exceed the minimum due to doze mode and constraints.
Common Mistakes with workmanager periodic
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro