Home » Android » android – WorkManager's PeriodicWorkRequest is executing once and not repeating

android – WorkManager's PeriodicWorkRequest is executing once and not repeating

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am trying to make use of WorkManager however I seem to be running into an issue where PeriodicSync is only repeated on startup once and that’s it.

I’ve looked at this post Is WorkManager's PeriodicWorkRequest really repeating for anyone? but there is no answer there. I am using the latest alpha build 10 as well.

If someone could help, it would be greatly appreciated. I am still new to android but need to get this to work for a project. I haven’t even tried using it with the code I want but simply trying to get it to run correctly.

I set it to run every 10 seconds, I also tried 10,000 ms but neither worked and nothing happened after 10 seconds.

The Log message “Sync” only appears once onCreate and that’s it.

Another issue I have is that every time I launch my app, it seems like the number of workers increases, as if they are getting added on top of each other and I don’t know if that’s related.
Answer to my other issue was found here but I still need help with my primary issue.

Here’s my code:

The Worker Class

public class MyWorker2 extends Worker {

    private static final String TAG = "BOOGABOOGA";

    public MyWorker2(
            @NonNull Context context,
            @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Worker.Result doWork() {

        // Do the work here--in this case, compress the stored images.
        // In this example no parameters are passed; the task is
        // assumed to be "compress the whole library."
        Log.i(TAG, "Sync");

        // Indicate success or failure with your return value:
        return Result.SUCCESS;

    }
}

MainActivity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        PeriodicWorkRequest syncWork = new PeriodicWorkRequest.Builder(MyWorker2.class, 10, TimeUnit.SECONDS).build();
        WorkManager.getInstance().enqueue(syncWork);

    }
}

Edit: Reason this isn’t working is because minimum interval to repeat a task is set to 15 minutes per the spec found here: https://developer.android.com/reference/androidx/work/PeriodicWorkRequest

How to&Answers:

Reason this wasn’t working was because the minimum time interval where a task can be repeated is set to 15 minutes. Credit goes to exshinigami. The spec for this can be found here: https://developer.android.com/reference/androidx/work/PeriodicWorkRequest#min_periodic_interval_millis

I just tested and verified that it did indeed repeat after 15 minutes.