Kotlin Task Scheduler: kotlinx.coroutines and Libraries for Background Tasks

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Task Scheduler in Kotlin: From Coroutines to Enterprise Solutions



Kotlin is a modern programming language actively used for creating server, mobile, and desktop applications. One of the key needs in such projects is executing tasks on a schedule or in the background. In this article, we will explore which Kotlin tools and libraries allow you to organize a task scheduler and provide practical code examples.



We will consider three main approaches:



  • Built-in Kotlin Coroutines (lightweight threads)
  • The WorkManager library for Android
  • The classic Quartz Scheduler with Kotlin wrappers


1. Scheduler Based on kotlinx.coroutines



kotlinx.coroutines is the standard library for asynchronous programming in Kotlin. It provides powerful tools for creating delayed and periodic tasks.



Main components:

  • delay() — delays the execution of a coroutine
  • launch and async — launching coroutines
  • CoroutineScope — lifecycle management
  • Dispatchers — selecting the execution thread


Example of a simple task scheduler repeating every 5 seconds:



import kotlinx.coroutines.*

fun main() = runBlocking { val job = launch { repeat(10) { i -> println("Task #$i executed at ${System.currentTimeMillis()}") delay(5000) // pause 5 seconds } } job.join() println("Scheduler finished work")}


For more complex scenarios (task cancellation, error handling, rate limiting), use Job and SupervisorJob:



val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())

fun schedulePeriodicTask(intervalMs: Long, action: suspend () -> Unit): Job { return scope.launch { while (isActive) { try { action() } catch (e: Exception) { println("Error: ${e.message}") } delay(intervalMs) } }}

// Usageval task = schedulePeriodicTask(2000) { println("Background task is running...")}

// Cancel after 10 secondsscope.launch { delay(10000) task.cancel() println("Task cancelled")}


Pros: lightweight, built-in cancellation support, integration with the Kotlin ecosystem. Cons: not suitable for Android applications that need to survive system restarts.



2. WorkManager for Android (Kotlin)



WorkManager is a library from Google for executing deferred and background tasks in Android, even after the app is closed or the device is rebooted. It works on top of coroutines.



Main steps:

  1. Create a class extending CoroutineWorker
  2. Implement the doWork() method
  3. Configure a WorkRequest (one-time or periodic)
  4. Enqueue the task via WorkManager


Example of a periodic task:



class MyPeriodicWorker(context: Context, params: WorkerParameters) :     CoroutineWorker(context, params) {

override suspend fun doWork(): Result { return try { // Your task: synchronization, cleanup, etc. println("Periodic task executed at ${System.currentTimeMillis()}") Result.success() } catch (e: Exception) { Result.retry() } }}

// Configuration and launchval constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build()

val periodicRequest = PeriodicWorkRequestBuilder&

Recommendations