Execute task every second using Work Manager API

前端 未结 2 1976
我寻月下人不归
我寻月下人不归 2021-02-07 05:09

Work Manager is a new API and I try to execute task every second, but it doesn\'t work.

This is my worker class

class TestingWorker : Worker(){
    overr         


        
相关标签:
2条回答
  • 2021-02-07 05:34

    Its not working because, the minimum interval between two periodic work request is 15 min which is defined by MIN_PERIODIC_INTERVAL_MILLIS.

    Based on the documentation:

    Creates a PeriodicWorkRequest to run periodically once every interval period. The PeriodicWorkRequest is guaranteed to run exactly one time during this interval. The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS. It may run immediately, at the end of the period, or any time in between so long as the other conditions are satisfied at the time.

    I would recommend you to avoid scheduling work so frequently. This will end up in consuming more resources and eventually impacting the battery life.

    0 讨论(0)
  • 2021-02-07 05:37

    WorkManager is not designed to run tasks every second, as it has two options to build work request that is and

    • PeriodicWorkRequest - runs repeated task every 15 mins, even if we change the time interval to anyhwere < 15 mins it will by default run for 15 mins only.
    • OneTimeWorkRequest - runs once

    WorkManager will enqueues the workrequests will call the respectively Worker classes to run the task where each workerclass overrides doWork() where the actual task is defined.

    This method runs in background thread and runs for 10mins after which the worker stops.

    Therefore if you want to schedule tasks running every second better the run foreground service or if your having running tasks in short duration.

    If you want to run background tasks for longer periods, best practice is to avoid it.

    0 讨论(0)
提交回复
热议问题