rial
rial

Reputation: 1015

android WorkRequest is running in an infinte loop

My task that I want to run is in doWork(). This part of the application begins when scheduleUpdateJob() is called. It in turn executes doWork() through a work request which does the operation. At the end of doWork(), updateSchedule() is called which sets a periodicRequest to execute doWork() every 15 minutes. My problem is that updateSchedule is immediately calling doWork which calls its calling funtion in an infinite loop. Am i doing something wrong.

public class EarthquakeUpdateWorker extends Worker {

    private static String PERIODIC_WORK_ID = "PERIODIC_WORK_ID";

    public EarthquakeUpdateWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    public static void scheduleUpdateJob(Context context) {
        WorkRequest workRequest = new OneTimeWorkRequest.Builder(EarthquakeUpdateWorker.class).setConstraints(Constraints.NONE).build();
        WorkManager workManager = WorkManager.getInstance();
        workManager.enqueue(workRequest);
  
    }

    @NonNull
    @Override
    public Result doWork() {
        // STUFF_TO_DO
        updateSchedule(getApplicationContext());
        return Result.success();
    }

    private static void updateSchedule(Context context) {
        Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.NOT_REQUIRED).build();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        Boolean autoUpdate = sharedPreferences.getBoolean(PreferenceActivity.PREF_AUTO_UPDATE, true);
        int updateFreq = Integer.parseInt(sharedPreferences.getString(PreferenceActivity.PREF_UPDATE_FREQ, "60"));

        if(autoUpdate) {
            PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).build();
            WorkManager workManager = WorkManager.getInstance();
            workManager.enqueue(workRequest);
           
        }
    }

}

Upvotes: 1

Views: 1511

Answers (2)

ctate
ctate

Reputation: 1409

Don't call updateSchedule() from your doWork() callback. Just schedule it as a periodic work request from the start, instead of a one-time that is then rescheduled as a periodic after it runs once.

This is the whole point of periodic work requests: they are repeated again later, automatically, until explicitly canceled.

Upvotes: 1

Navjot
Navjot

Reputation: 1294

Set initial delay while creating the PeriodicWorkRequest

Replace:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).build();

With:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).setInitialDelay(updateFreq, TimeUnit.MINUTES).build();

Upvotes: 1

Related Questions