The WorkManager plugin manages background tasks via the Android WorkManager API, supporting constraint-based one-time and periodic scheduling.

Setup

The WorkManager plugin is already registered in the default AppTemplate.

Android Manifest

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />

API

workmanager.NewPlugin() *WorkManagerPlugin

Creates a new WorkManager plugin instance.

(*WorkManagerPlugin).RegisterTask(name string, fn TaskFunc)

Registers a task function that can be executed by WorkManager.

type TaskFunc func() error

(*WorkManagerPlugin).EnqueueOneTime(taskKey string, constraints *Constraints) (string, error)

Schedules a one-time background task.

(*WorkManagerPlugin).EnqueuePeriodic(taskKey string, intervalMinutes int, constraints *Constraints, replaceExisting bool, runImmediate bool) (string, error)

Schedules a repeating background task using enqueueUniquePeriodicWork.

Argument Type Description
taskKey string Unique task identifier used as the WorkManager unique name
intervalMinutes int Repeat interval in minutes (minimum 15)
constraints *Constraints Execution constraints
replaceExisting bool If true, replaces any existing periodic work with the same taskKey (REPLACE). If false, keeps the existing work (KEEP)
runImmediate bool If true, also enqueues a one-time execution of the task immediately, in addition to the periodic schedule

(*WorkManagerPlugin).IsEnqueued(taskKey string) (bool, error)

Checks if a task is currently scheduled.

(*WorkManagerPlugin).CancelAll() string

Cancels all scheduled tasks.

workmanager.DefaultConstraints() Constraints

Returns default constraints (network not required).

Constraints

type Constraints struct {
    NetworkType           string // CONNECTED, UNMETERED, NOT_ROAMING, NOT_REQUIRED
    RequiresCharging      bool
    RequiresDeviceIdle    bool
    RequiresBatteryNotLow bool
    RequiresStorageNotLow bool
}

Example

import "github.com/sweet-juice/sweetjuice/plugins/workmanager"

// Register a background task
workmanager.NewPlugin().RegisterTask("sync_data", func() error {
    // Your background logic here
    return nil
})

// Schedule it to run every 15 minutes, keeping any existing work
workmanager.NewPlugin().EnqueuePeriodic("sync_data", 15, nil, false, false)

// Schedule it to run every 15 minutes, replacing existing work, and run immediately
workmanager.NewPlugin().EnqueuePeriodic("sync_data", 15, nil, true, true)

Events

workmanager:execute

Fired when a background task executes. Payload includes task key and input data.

workmanager:result

Fired when a task completes. Payload:

{
  "task_key": "sync_data",
  "result": "success",
  "error": ""
}

Notes

  • Android only. iOS uses BGTaskScheduler instead.
  • Tasks must be registered before they can be enqueued.
  • Tasks run even if the app is killed (system-managed).