harikrishnan
harikrishnan

Reputation: 1945

Schedule a Particular task on every Friday via WorkManager API

I am using workmanager to send sms at every Friday for reminder purpose. even, app is closed state also. sample:

PeriodicWorkRequest periodicWork = new 
    PeriodicWorkRequest.Builder(MyWorker.class, 7, TimeUnit.DAYS).build();
WorkManager.getInstance().enqueue(periodicWork);

can anyone help on this. Thanks.

Note: I have this onetime request. its working fine. even, app is closed also.

WorkManager workManager = WorkManager.getInstance();
workManager.enqueue(new OneTimeWorkRequest.Builder(MyWorker.class).build());

If suppose, workmanager is not possible, please suggest any other api also in android.

Already Refereed this link also: its not working. Schedule a work on a specific time with WorkManager

Upvotes: 3

Views: 3255

Answers (4)

Patriotic
Patriotic

Reputation: 2300

Below steps might be helpful:

  1. Use the Alarm Manager Api to trigger a pending intent.
  2. Do step 1 after receiving the broadcast.
  3. Do step 1 after the device rebooted(BOOT_COMPLETED) using another Broadcast Receiver.

Upvotes: 0

UdayaLakmal
UdayaLakmal

Reputation: 4223

Can use AlarmManager (not tried with workmanager, but with following way with AlarmManager tested and working).

This execute once a week on Friday, you need register Broadcast receiver to receive intent, so that you can do your sms sending on Receive..

    PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("RECIVER"), 0 );

    AlarmManager alarm = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
    Calendar timeOff = Calendar.getInstance();
    int days = Calendar.FRIDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); 
    timeOff.add(Calendar.DATE, days);
    timeOff.set(Calendar.HOUR, 12);
    timeOff.set(Calendar.MINUTE, 0);
    timeOff.set(Calendar.SECOND, 0);

    alarm.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pintent);

Upvotes: 0

Dinesh
Dinesh

Reputation: 988

WorkManager is a wrong choice for this use case.

Why?

WorkManager is intended for tasks that are deferrable—thatis, not required to run immediately—and required to run reliably even if the app exits or the device restarts.

You should be using AlarmManager if you want your task to be run exactly at some point of time.

Upvotes: 0

Michael Dovoh
Michael Dovoh

Reputation: 121

Not the best solution but it works. Use PeriodicWorkRequest and schedule the task daily. Then use jodatime library and check if the day is Friday. If it's Friday execute the task. If not cancel the task. Based on the first execution you can manipulate the PeriodicWorkRequest to schedule every Friday by adding 6 to the request.

Upvotes: 1

Related Questions