Anandasok
Anandasok

Reputation: 1

Kotlin WorkManager: Scheduling a Periodic POST API Call Every 15 Minutes with Persistence Across Reboots

I'm trying to use Kotlin's WorkManager to schedule a POST API call that runs every 15 minutes and continues to execute even after the device restarts or reboots. Here’s what I’m aiming for:

The task should make a POST API call with a JSON payload. It should execute every 15 minutes. The task should persist across device reboots so it continues without requiring any user interaction or app relaunch.

class ApiWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        return try {
            val client = OkHttpClient()
            val jsonObject = JSONObject().apply {
                put("key1", "value1")
                put("key2", "value2")
            }
            val requestBody = RequestBody.create(
                "application/json".toMediaTypeOrNull(),
                jsonObject.toString()
            )

            val request = Request.Builder()
                .url("https://yourapiendpoint.com/yourpostendpoint")
                .post(requestBody)
                .build()

            val response = client.newCall(request).execute()
            if (response.isSuccessful) {
                Result.success()
            } else {
                Result.retry()
            }
        } catch (e: Exception) {
            Result.retry()
        }
    }
}

fun scheduleApiWorker(context: Context) {
    val workRequest = PeriodicWorkRequestBuilder<ApiWorker>(15, TimeUnit.MINUTES)
        .setConstraints(
            Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresBatteryNotLow(true)
                .build()
        )
        .build()

    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
        "ApiWorker",
        ExistingPeriodicWorkPolicy.KEEP,
        workRequest
    )
}

Is this the correct way to set up a periodic WorkManager task that will run every 15 minutes, even after a system reboot?

Upvotes: 0

Views: 40

Answers (1)

Umang Thakkar
Umang Thakkar

Reputation: 234

As per this doc:

Work is persistent when it remains scheduled through app restarts and system reboots.

so, your work will be resumed automatically.

Upvotes: 0

Related Questions