Skip to content

Unified API for scheduling and managing background tasks—one‑off, periodic, exact and chained jobs—featuring advanced triggers, structured logging, event‑driven completion, demo UI and docs.

License

Notifications You must be signed in to change notification settings

vietnguyentuan2019/KMPTaskManager

Repository files navigation

⚡ KMP TaskManager

The Most Powerful Background Task Scheduler for Kotlin Multiplatform

Write once, schedule anywhere. Unified API for background tasks on Android & iOS.

Maven Central Kotlin License

klibs.io GitHub Stars Build

📖 Documentation🚀 Quick Start💡 Examples📦 Migration to v3.0


🎉 What's New in v3.0.0

  • 🚀 60% Faster iOS - File-based storage replaces NSUserDefaults
  • 🎯 Better API Design - SystemConstraint replaces trigger/constraint confusion
  • Smart Exact Alarms - Auto-fallback when permission denied (Android 12+)
  • 🔋 Heavy Task Support - New KmpHeavyWorker for long-running tasks
  • 🔔 AlarmReceiver Base - Easy exact alarm implementation
  • 🛡️ Thread-Safe iOS - File locking + duplicate detection

See Full Migration Guide | Breaking Changes: Deprecated triggers (backward compatible)


Why KMP TaskManager?

Before: The Problem

// Android - WorkManager
val androidWork = OneTimeWorkRequestBuilder<SyncWorker>()
    .setConstraints(/* ... */)
    .build()
WorkManager.getInstance(context).enqueue(androidWork)

// iOS - Different API!
BGTaskScheduler.shared.submit(BGAppRefreshTaskRequest(/* ... */))

Different APIs. Double the code. Double the bugs.

After: KMP TaskManager

// One API for both platforms!
scheduler.enqueue(
    id = "data-sync",
    trigger = TaskTrigger.Periodic(15_MINUTES),
    workerClassName = "SyncWorker",
    constraints = Constraints(requiresNetwork = true)
)

Single unified API. Shared code. Zero headaches.


🚀 Get Started in 5 Minutes

1. Add Dependency

kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("io.github.vietnguyentuan2019:kmptaskmanager:3.0.0")
        }
    }
}

2. Initialize (One Time)

Android - Application.kt

startKoin {
    androidContext(this@MyApp)
    modules(kmpTaskManagerModule())
}

iOS - AppDelegate.swift

KoinIOSKt.doInitKoinIos()
registerBackgroundTasks()

3. Schedule Your First Task

class MyViewModel(private val scheduler: BackgroundTaskScheduler) {

    fun scheduleSync() = viewModelScope.launch {
        scheduler.enqueue(
            id = "data-sync",
            trigger = TaskTrigger.Periodic(intervalMs = 15_MINUTES),
            workerClassName = "SyncWorker",
            constraints = Constraints(requiresNetwork = true)
        )
    }
}

That's it! Your task runs on both Android and iOS!


Core Features

Periodic Data Sync

scheduler.enqueue(
    id = "user-data-sync",
    trigger = TaskTrigger.Periodic(intervalMs = 15_MINUTES),
    workerClassName = "SyncWorker",
    constraints = Constraints(requiresNetwork = true)
)

Task Chains (Sequential & Parallel)

// Execute tasks in sequence: Download → Process → Upload
scheduler
    .beginWith(TaskRequest(workerClassName = "DownloadWorker"))
    .then(TaskRequest(workerClassName = "ProcessWorker"))
    .then(TaskRequest(workerClassName = "UploadWorker"))
    .enqueue()

// Run tasks in parallel, then finalize
scheduler
    .beginWith(listOf(
        TaskRequest("SyncWorker"),
        TaskRequest("CacheWorker"),
        TaskRequest("CleanupWorker")
    ))
    .then(TaskRequest("FinalizeWorker"))
    .enqueue()

Battery-Aware Tasks (v3.0+ API)

scheduler.enqueue(
    id = "ml-training",
    trigger = TaskTrigger.OneTime(),
    workerClassName = "MLTrainingWorker",
    constraints = Constraints(
        isHeavyTask = true,
        requiresCharging = true,
        systemConstraints = setOf(
            SystemConstraint.REQUIRE_BATTERY_NOT_LOW,
            SystemConstraint.DEVICE_IDLE
        )
    )
)

Exact Alarms with Auto-Fallback (Android)

// v3.0+: Automatically falls back to WorkManager if permission denied
class MyScheduler(context: Context) : NativeTaskScheduler(context) {
    override fun getAlarmReceiverClass() = MyAlarmReceiver::class.java
}

scheduler.enqueue(
    id = "reminder",
    trigger = TaskTrigger.Exact(atEpochMillis = System.currentTimeMillis() + 60_000),
    workerClassName = "ReminderWorker"
)

See 10+ Examples →


Key Features

Feature KMP TaskManager Others
Unified API (Android + iOS)
9 Trigger Types 1-2
Task Chains (Sequential & Parallel)
Smart Retry with Backoff
Real-time Event System
Exact Alarm Auto-Fallback ✅ v3.0
Heavy Task Support ✅ v3.0
Production Ready ✅ v3.0.0 ⚠️ Beta

Trigger Types

  • Periodic - Repeat at intervals (15 min minimum)
  • OneTime - Run once with optional delay
  • Exact - Precise timing (alarms, reminders)
  • ContentUri - React to media changes (Android)
  • Windowed - iOS time window (not implemented)

System Constraints (v3.0+)

constraints = Constraints(
    requiresNetwork = true,
    requiresCharging = true,
    systemConstraints = setOf(
        SystemConstraint.REQUIRE_BATTERY_NOT_LOW,  // Battery > 15%
        SystemConstraint.DEVICE_IDLE,              // Device idle
        SystemConstraint.ALLOW_LOW_STORAGE,        // Allow when storage low
        SystemConstraint.ALLOW_LOW_BATTERY         // Allow when battery low
    )
)

Smart Retry

constraints = Constraints(
    backoffPolicy = BackoffPolicy.EXPONENTIAL,
    backoffDelayMs = 10_000  // 10s → 20s → 40s → 80s...
)

Platform Support

Android

  • WorkManager integration
  • AlarmManager exact scheduling
  • Exact alarm auto-fallback (v3.0)
  • KmpHeavyWorker foreground service (v3.0)
  • Expedited work support
  • ContentUri triggers (MediaStore)

iOS

  • BGTaskScheduler integration
  • File-based storage - 60% faster (v3.0)
  • Batch execution (3x faster)
  • Thread-safe file operations (v3.0)
  • Duplicate detection (v3.0)
  • Timeout protection

Documentation


Why Not Alternatives?

vs. Native APIs (WorkManager / BGTaskScheduler)

  • Native APIs: Different code for each platform, hard to maintain
  • KMP TaskManager: Single API, shared code, maintainable

vs. Other KMP Libraries

  • Others: Limited features (1-2 triggers), no chains, pre-release
  • KMP TaskManager: 9 triggers, task chains, production-ready v3.0

Detailed Comparison


Production-Ready

Version Lines of Code Test Coverage

  • Fully Tested - 100+ test cases covering edge cases
  • Type-Safe - 100% Kotlin with strong typing
  • Well Documented - Comprehensive guides & API docs
  • Actively Maintained - Regular updates and bug fixes
  • Production Proven - Used in real-world apps

Contributing

We love contributions! Here's how you can help:

Contributing Guide


Quick Links


License

Copyright © 2025 Nguyễn Tuấn Việt

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

⭐ Star Us on GitHub!

If KMP TaskManager saves you time, please give us a star!

It helps other developers discover this project.

⬆️ Back to Top


Made with ❤️ by Nguyễn Tuấn Việt

Support: [email protected]Community: GitHub Issues

About

Unified API for scheduling and managing background tasks—one‑off, periodic, exact and chained jobs—featuring advanced triggers, structured logging, event‑driven completion, demo UI and docs.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors 2

  •  
  •