I am trying to implement a periodic task that should run every 5 mins and check the connectivity of my device to certain URLs every 5 mins. I want to use WorkManager for this. However, the minimum period for PeriodicWorkRequest is 15 mins. I am wondering if can I create a recurring OneTimeWorkRequest that will enqueue another OneTimeWorkRequest with an initial delay of 5 mins to achieve the period of 5 mins? What are the potential downsides of doing it? Note: In my use case, the device is always connected to power so Doze mode won't kick in. I am thinking of a code somewhat similar to like below:

public class NetworkCheckWorker extends Worker {

    private static final String TAG = "NetworkCheckWorker";

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

    @NonNull
    @Override
    public Result doWork() {
        // Perform network connectivity check
        boolean isConnected = isConnectedToEndpoint();

        // Always retry connecting, regardless of connectivity status
        Log.d(TAG, "Retrying connectivity in 5 minutes");
        scheduleRetryWork();

        // Indicate that the work was successful
        return Result.success();
    }

    private boolean isConnectedToEndpoint() {
        // Implement code to check network connectivity to the endpoint
        return true; 
    }

    private void scheduleRetryWork() {
        // Create a new work request for retrying after 5 minutes
        OneTimeWorkRequest retryWorkRequest = new OneTimeWorkRequest.Builder(NetworkCheckWorker.class)
                .setInitialDelay(5, TimeUnit.MINUTES)
                .build();

        // Enqueue the retry work request
        WorkManager.getInstance(getApplicationContext()).enqueue(retryWorkRequest);
    }
}

Yet to try out this code for full functionality. Want an opinion from the community if this is even something suggested or has some downside?

0

There are 0 best solutions below