1

I want to schedule 2 different periodic task, for this I am using work manager. 1. Upload file to server - after every 20 min 2. Call API in - after every 15 min

For API call (Daily operation) following is my code:

PeriodicWorkRequest.Builder dailyWorkBuilder =
            new PeriodicWorkRequest.Builder(CheckAccount.class, 15,
                    TimeUnit.MINUTES)
                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build());
    PeriodicWorkRequest DailyJob = dailyWorkBuilder.build();
    WorkManager.getInstance().enqueueUniquePeriodicWork("DailyJob", ExistingPeriodicWorkPolicy.REPLACE,DailyJob);

To upload file I am using following code:

PeriodicWorkRequest.Builder wifiWorkBuilder =
                        new PeriodicWorkRequest.Builder(FileUpload.class, 20,
                                TimeUnit.MINUTES)
                                .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build());
                PeriodicWorkRequest wifiWork = wifiWorkBuilder.build();
                WorkManager.getInstance().enqueueUniquePeriodicWork("wifiJob", ExistingPeriodicWorkPolicy.REPLACE,wifiWork);

Now here I am facing 2 difficulties: 1. If I open app - Lets say after open app my Activity is HomeActivity in this activity I had written dailyWorkBuilder code (which executes after every 20 min) will get called every time I open app. If I did not open app it will get called after 20 min but before 20 min I open app it gets called. So here I want to check if task is not running then only it should execute not every time when I open app

  1. It also call wifiWorkBuilder (task which execute after every 15 min)it also get called every time when I open app. These 2 task are totally different and not depend on each other, but still if one task get called other will also get called before there specified time.

Whats wrong in above code. Any suggestion will be appreciated. Thanks

PPD
  • 5,660
  • 12
  • 52
  • 86

1 Answers1

0

I had same problem some days ago. I managed that by-

Schedule work if Work-Manager is not scheduled already.

In your MainActivity where you set work.

if(isWorkScheduled("DailyJob")){
  // now schedule DailyJob
}

I also asked a question and answered after getting solution.

private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    if (instance == null) return false;
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    return statuses.getValue() != null && statuses.getValue().size() > 0;
}

This is up to you if you consider below method. It will return true when some of its task is RUNNING or ENQUEUED.

private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    if (instance == null) return false;
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    if (statuses.getValue() == null) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses.getValue()) {
        running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
    }
    return running;
}

Suggestion

  • Always null check WorkManager object, because it can be null in some cases. You can see doc.
 * @return The singleton instance of {@link WorkManager}; this may be {@code null} in unusual
 *         circumstances where you have disabled automatic initialization and have failed to
 *         manually call {@link #initialize(Context, Configuration)}.
  • Use ExistingPeriodicWorkPolicy.KEEP instead of ExistingPeriodicWorkPolicy.REPLACE, if your every task is important, work manager will auto start next work after its completion.
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • hi @Khemraj, thanks for suggestion, I had tried both methods isWorkScheduled(String tag) but both always returns false. For first time it must returns false, but next time it should returns true. But everytime it returns false only – PPD Aug 28 '18 at 09:38
  • Then you have to find it out. Because `getStatusesByTag` returns status by tag. – Khemraj Sharma Aug 28 '18 at 09:47
  • You are using same tag to create work and `getStatusesByTag()`, right. – Khemraj Sharma Aug 28 '18 at 09:47
  • Also try with fresh install, perhaps some old work is scheduled there. – Khemraj Sharma Aug 28 '18 at 09:48
  • Hi tried 2-3 times uninstalling and then again installing app. Using same tag for creating work i.e "DailyJob". Thanks I will find out what is going on. – PPD Aug 28 '18 at 09:49
  • 1
    Yes, you will find it. It was solution that worked for me. Check with one work for now. – Khemraj Sharma Aug 28 '18 at 09:52