Search code examples
androidandroid-workmanager

Android schedule PeriodicWorkRequest only for n times


Android Periodic work will run periodically but i need to schedule a task for n time. Suppose i want to run a task every day for 20 days only. I didn't find any way to do that.

How can i do that?


Solution

  • The offered API allows to cancel a work unconditionally:

    If you no longer need your previously enqueued work to run, you can ask for it to be cancelled. Work can be cancelled by its name, id or by a tag associated with it.

    But you can use your favorite storage to tack the number of days until they reach to 20 days. And every time the work is performed; i.e. when the doWork() callback gets called; you can increment the no. of days.

    Here's an example of SharedPreference:

    public static final String WORK_TAG = "WORK_TAG";
    public static final String DAY_NO = "DAY_NO";
    
    @androidx.annotation.NonNull
    @Override
    public Result doWork() {
    
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("prefs", MODE_PRIVATE);
        int dayNo = prefs.getInt(DAY_NO, 1);
        
        if (dayNo == 23) {
            // cancel the work
            WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(WORK_TAG);
            Log.d(TAG, "The periodic work has been stopped");
    
        } else {
            // Increment the number of days
            dayNo++;
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("DAY_NO", dayNo);
            editor.apply();
    
            // Do your work here
            
        }
    
        return Result.success();
    
    }
    

    Make sure that you tag the work with the same tag when you initialize the workRequest:

    PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(
            MyWorkerclass.class, // Worker class
            .......
            .addTag(WORK_TAG)
            .build();
    

    Also notice that any other work with the same tag will be cancelled as well, so make sure it's a unique tag.