Chrystian
Chrystian

Reputation: 1047

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()
    }

Upvotes: 1

Views: 1085

Answers (2)

Raunak Sett
Raunak Sett

Reputation: 324

A better approach would be to set the flex interval so that job would executed at the end of your specified time interval say 12 hours set the flext interval as 1 hour. Your job will run between the last hour of every 12 hours.

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

Upvotes: 0

Kasım Özdemir
Kasım Özdemir

Reputation: 5634

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

Upvotes: 2

Related Questions