WorkManager google api: wait 15 minutes for every periodic worker execution?

社会主义新天地 提交于 2020-07-06 11:37:17

问题


Is there a way to test a PERIODIC worker from WorkManager Google API without waiting at least 15 minutes for every execution?

I mean, it is a DEBUG app and I'm running it through Android Studio and I don't want to wait such a long time to test my features.


回答1:


You can't.

Periodic work has a minimum interval of 15 minutes and it cannot have an initial delay. You can find the proof in the WorkSpec.java class.

 /**
     * Sets the periodic interval for this unit of work.
     *
     * @param intervalDuration The interval in milliseconds
     */
    public void setPeriodic(long intervalDuration) {
        if (intervalDuration < MIN_PERIODIC_INTERVAL_MILLIS) {
            Logger.get().warning(TAG, String.format(
                    "Interval duration lesser than minimum allowed value; Changed to %s",
                    MIN_PERIODIC_INTERVAL_MILLIS));
            intervalDuration = MIN_PERIODIC_INTERVAL_MILLIS;
        }
        setPeriodic(intervalDuration, intervalDuration);
    }

But there are other ways to deal with that.

  1. Write unit tests using work-testing library and ensure that your business logic works as expected.
  2. Use dependency injection approach and provide a OneTimeWorkRequest in debug mode, for example:
interface Scheduler {
    fun schedule()
}

class DebugScheduler {
    fun schedule() {
        WorkManager.getInstance().enqueue(
            OneTimeWorkRequest.Builder(MyWorker::class.java)
                .build()
        )
    }
}

class ProductionScheduler {
    fun schedule() {
        // your actual scheduling logic
    }
}



回答2:


For testing purposes, you can use the work-testing library as shown here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/testing

Specifically, you want to look at how to test periodic work: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/testing#periodic-work



来源:https://stackoverflow.com/questions/55172192/workmanager-google-api-wait-15-minutes-for-every-periodic-worker-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!