Scheduler
Run periodic, calendar, and on-boot background tasks from Kotlin that the OS fires on schedule, even when your app is closed.
The scheduler module runs background tasks on a schedule, even when your app is closed. You
register a task once and the OS fires it. Add
implementation("dev.nucleusframework:nucleus.scheduler:3.0.0"); it exposes
kotlinx-serialization-json, so apply kotlin("plugin.serialization") for @Serializable task
input.
schedulerGradle plugin: RecommendedWindow runtime: Not neededTasks relaunch the packaged executable; in development they relaunch java.Schedule a task
Implement DesktopTask, register it under a TaskId, and hand scheduler launches to
DesktopBootReceiver at the top of main():
val SyncId = TaskId("sync")
class SyncTask : DesktopTask {
override suspend fun doWork(context: TaskContext): TaskResult {
performSync()
return TaskResult.Success
}
}
val registry = TaskRegistry.Builder().register(SyncId) { SyncTask() }.build()
fun main(args: Array<String>) {
if (DesktopBootReceiver.isSchedulerInvocation(args)) {
DesktopBootReceiver.handle(args = args, registry = registry)
return
}
nucleusApplication(args) { /* ... */ }
}Run this check before nucleusApplication. Otherwise each scheduled run opens a window.
Then enqueue a request. Enqueuing the same id twice is a no-op by default (see
TaskRequest).
val scheduler = DesktopTaskScheduler.getInstance()
scheduler.enqueue(TaskRequest.periodic(SyncId, 1.hours)) // counted from enqueue time
scheduler.enqueue(TaskRequest.calendar(ReportId, CronExpression.everyDayAt(LocalTime.of(9, 0))))
scheduler.enqueue(TaskRequest.onBoot(StartupCheckId)) // at loginCheck the macOS sandbox
On macOS, enqueue returns false when ExecutableRuntime.isSandboxed() is true. Fall back to
Service management:
if (ExecutableRuntime.isSandboxed()) {
AppServiceManager.register(AppService.Agent("com.example.myapp.sync"))
} else {
DesktopTaskScheduler.enqueue(TaskRequest.periodic(SyncId, 1.hours))
}A Developer ID PKG (appStore = false) is unsandboxed and can schedule tasks; the App Store PKG
cannot. See Executable type.
Notes
inputDatais stored as plain JSON on disk. Store a reference, not a secret.CronExpression.everyHour()fires at the top of each wall-clock hour, unlikeperiodic(id, 1.hours).- On macOS, an uninstall leaves the entries in place. Call
cancelAll()from your sign-out or reset flow. - Inside a Flatpak,
isAvailable()returnsfalseandenqueuereturnsfalse: systemd cannot reach the sandboxed app. - To test tasks without the OS, see Scheduler testing.
API reference
DesktopTaskScheduler
isAvailable(), enqueue(request), cancel(taskId), cancelAll(), isScheduled(taskId),
getTaskInfo(taskId): TaskInfo? (state, last and next run, run count, last result), and
getAllTasks(). enqueue returns true when scheduled or already present.
TaskRequest
periodic(taskId, interval) (15 minutes minimum, shorter throws), calendar(taskId, expression),
or onBoot(taskId), each with an optional builder:
TaskRequest.periodic(SyncId, 1.hours) {
inputData(SyncInput(endpoint = "https://api.example.com"))
runImmediately() // also run once at registration (periodic only)
constraints { requiredNetworkType = NetworkType.UNMETERED }
existingTaskPolicy(ExistingTaskPolicy.REPLACE) // KEEP (default), UPDATE_DATA, REPLACE
}retryPolicy(RetryPolicy.Linear | ExponentialBackoff) is stored but not applied yet.
CronExpression: everyDayAt(time), everyWeekdayAt(time) (Monday to Friday),
everyWeekdayAt(day, time), everyHour().
TaskResult: Success, Failure(message) (no retry), Retry(message) (one re-run about
5 minutes later).
Constraints
Checked when the task fires. An unmet periodic run waits for the next trigger; an unmet calendar or on-boot run retries once about 5 minutes later.
| Property | Description |
|---|---|
requiredNetworkType | NOT_REQUIRED, CONNECTED, or UNMETERED. |
requiresBatteryNotLow | Battery above 15 %. No battery passes. |
requiresCharging | Plugged in. |
requiresDeviceIdle | No user input for at least 5 minutes. |
minimumStorageBytes | Minimum free space on the app partition. |
SchedulerConfig
If your app starts through a custom launcher, point the scheduler at it before the first
enqueue. A later change only affects tasks enqueued afterwards.
SchedulerConfig.executablePath = "/opt/myapp/myapp-launcher" // absolute; null = current executable
SchedulerConfig.executableArguments = listOf("--background") // before --nucleus-scheduler-runWhat's next
- Scheduler testing: run tasks in memory with virtual time.
- Service management: background agents for sandboxed macOS builds.
- System info: the signals behind the constraints.
- Auto-launch: start the app itself at login.
Last updated on