Search code examples
androidandroid-workmanager

Is there a way to not execute the worker on first app launch


Background: I am using WorkManager for updating the local cache every 2 days. This is configured in the Application class, so that it gets scheduled immediately on app launch.

Problem: The worker gets executed immediately on first app launch instead of scheduling it.

Code:

        val configuration = Configuration.Builder()
                .setWorkerFactory(workerFactory)
                .setMinimumLoggingLevel(Log.DEBUG)
                .build()
        WorkManager.initialize(appContext, configuration)
        val workRequest = PeriodicWorkRequestBuilder<ConfigWorker>(2, TimeUnit.DAYS)
                .build()

        val workManager = WorkManager.getInstance(appContext)
        workManager.enqueueUniquePeriodicWork(
                "config_worker_request",
                ExistingPeriodicWorkPolicy.KEEP,
                workRequest
        )

I was actually looking for something which doesn't execute the worker immediately after enqueued. Is there an option?

I can use a flag for the first app launch and solve this, but I am looking for an option from WorkManager library itself.


Solution

  • You should set an initial delay on your PeriodicWorkRequest (for example, by using this method: https://developer.android.com/reference/androidx/work/WorkRequest.Builder#setInitialDelay(long,%20java.util.concurrent.TimeUnit) ).