Search code examples
androidandroid-workmanager

WorkManager PeriodicWorkRequest running inmediately


I created a periodic WorkManager to send a notification after 12 hours. The problem is that when I send the call to schedule the WorkManager the work is done immediately, and also on schedule 12 hours later. I do not want the WorkManager to get executed immediately, but at the scheduled amount of hour later.

Call from MainClass:

  Constraints constraints = new Constraints.Builder()
                //wifi only
                .setRequiredNetworkType(NetworkType.UNMETERED)
                .build();

        PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(WorkManagerCheckReport.class, 12, TimeUnit.HOURS)
                .addTag(TAG)
                .setConstraints(constraints)
                .build();

    WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(TAGWORKMANAGER, ExistingPeriodicWorkPolicy.KEEP, periodicWork);

WorkManager class:

class WorkManagerCheckReport(context: Context, params: WorkerParameters) : Worker(context, params) {

    var id = 0
    private val TAG = "WorkManagerCheckReport"

    //flag to keep track if document is available to the patient.
    private var flagReportNotification = false
    private var isReportNOTAvailableToPatient = false

    override fun doWork(): Result {
        Customer.log(TAG, "Workmanager called.")

        id = inputData.getLong(NOTIFICATION_ID, 0).toInt()

        sendNotification()

        return success()
    }

Solution

  • You can try this:

    PeriodicWorkRequest periodicWork = new 
    PeriodicWorkRequest.Builder(WorkManagerCheckReport.class, 12, TimeUnit.HOURS)
                .addTag(TAG)
                .setConstraints(constraints)
                .setInitialDelay(12, TimeUnit.HOURS)
                .build();
    

    Sets an initial delay for the WorkRequest