Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enqueue WorkManager OneTimeWorkRequest at specific time

I have a scenario where i have to give user notification using WorkManager at specific time.

How can i schedule Work at specific time, and it should show up even if user force kills the app. or app is not running.

My Current code is as below :

Data d = new Data.Builder().putInt(IntentConstants.SCHEDULE_ID, scheduleData.getScheduleID()).build();
OneTimeWorkRequest compressionWork =
    new OneTimeWorkRequest.Builder(ScheduleWorker.class)
        .setInputData(d)
        .build();
WorkManager.getInstance().enqueue(compressionWork);
like image 680
Parth Patel Avatar asked Oct 21 '25 14:10

Parth Patel


1 Answers

I think i have found an easy and working solution. It works 100%.

We have to get current time in milliseconds and required specific time to trigger it in milliseconds then you have to calculate specific time - current time.

I have my solution (working code below) :

Data d = new Data.Builder()
             .putInt(IntentConstants.SCHEDULE_ID, scheduleData.getScheduleID())
             .build();

long currentTime= System.currentTimeMillis();
long specificTimeToTrigger = c.getTimeInMillis();
long delayToPass = specificTimeToTrigger - currentTime;

OneTimeWorkRequest compressionWork =
                        new OneTimeWorkRequest.Builder(ScheduleWorker.class)
                                .setInputData(d)
                                .setInitialDelay(delayToPass, TimeUnit.MILLISECONDS)
                                .build();

WorkManager.getInstance().enqueue(compressionWork);

Main Logic is in the delayToPass = currentTime (in Millis) - specificTimeToTrigger (in Millis)

like image 96
Parth Patel Avatar answered Oct 23 '25 03:10

Parth Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!