How to set minimum time interval in `WorkManager` - android

I have set time interval in PeriodicWorkRequest 15 min but some time its executing before 15 min interval
This is my code
// START Worker
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(LocationWorker.class, 15,
TimeUnit.MINUTES)
.addTag(TAG)
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.KEEP, periodicWork);
Please suggest what i did wrong or how can I execute my code exactly after 15 min

Related

android-execute a worker at roughly the same time every day

according to this medium article from Android Developers:
At the moment, if you need to execute a worker at roughly the same time, every day, your best option is to use a OneTimeWorkRequest with an initial delay so that you execute it at the right time:
and then when the work finishes successfully, the idea is to reschedule the work to be run once again and so on. now my question is that if we want a work to be repeated everyday at roughly the same time, why can't we directly use work manager PeriodicWorkRequest? for example suppose the work must be repeated everyday around 5:00 PM. then:
Calendar windowStart = new GregorianCalendar();
windowStart.set(Calendar.HOUR_OF_DAY, 17);
windowStart.set(Calendar.MINUTE, 0);
windowStart.set(Calendar.SECOND, 0);
windowStart.set(Calendar.MILLISECOND, 0);
long delay = windowStart.getTimeInMillis() - System.currentTimeMillis();
if (delay < 0) {
windowStart.add(Calendar.DAY_OF_MONTH, 1);
delay = windowStart.getTimeInMillis() - System.currentTimeMillis();
}
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
PeriodicWorkRequest periodicWorkRequest =
new PeriodicWorkRequest.Builder(Worker.class, 24, TimeUnit.HOURS, 5, TimeUnit.MINUTES)
.setInitialDelay(delay, TimeUnit.MILLISECONDS)
.setConstraints(constraints)
.build();
does this piece of code guarantee that the work will definitely run everyday between 17:00 and 17:05, if the constraints are met?

WorkManager - Can WorkRequest maximum backoff time for retries be changed?

I'm using WorkManager to queue up OneTimeWorkRequests for file uploads. This of course requires network connectivity, and if the device does not have connectivity and the upload fails, it will retry as per my specified retry/backoff policy.
My question is simply:
Can I change the maximum backoff time for the retry?
The maximum backoff time is set to 5 hours by default and I would ideally like to reduce this, but I have not been able to find a way to do so.
See my code for enqueueing a work request below:
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest uploadRequest = new OneTimeWorkRequest.Builder(UploadFileWorker.class)
.setInputData(createInputDataForUri(file.getPath()))
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS)
.build();
workManager.enqueueUniqueWork(UNIQUE_WORK_FILE_UPLOAD, ExistingWorkPolicy.APPEND, uploadRequest);
We can easily set the BackoffPolicy (linear/exponential) and backoffDelay with .setBackoffCriteria(), as well as add an initial delay to the request, but I see no way to customise the maximum backoff time for the retry. Is this by design, or am I just blind?

Schedule a task weekly using Firebase job dispatcher

Have tried job dispatcher for scheduling repetitive tasks on Hourly basis. Have written a code snippet for the problem but not sure if this is a correct implementation or not.
Snippet is for scheduling a task at 11 Hour of Monday at every week.
Any correction on this or other possible solution will help a lot.
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c1.set(Calendar.HOUR_OF_DAY, 11);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);
c1.set(Calendar.MILLISECOND, 0);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(Splash_onboarding.this));
Job myJob = dispatcher.newJobBuilder()
.setService(ScheduledNotificationService.class)
.setTag(dispatcherTag)
.setRecurring(true)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(Math.round(c1.getTime().getTime() / 1000), (Math.round(c1.getTime().getTime() / 1000)) + 60))
.setReplaceCurrent(true)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.build();
dispatcher.mustSchedule(myJob);
I don't think you are implementing Firebase JobDispatcher correctly
Trigger.executionWindow()
In this, you write after how much time your job executes itself after scheduling your job. For more info see this :
https://stackoverflow.com/a/42111723/7384780
You can solve your problem by scheduling your first non-recurring job with executionWindow (get time of next monday) - System.currentTimeMillis() and then starting a recurring job inside JobService with executionWindow of 7 * 24 * 60 * 60.

How do we use setMinimumLetancy using FirebaseJobDispatcher?

I am using FirebaseJobDispatcher for posting the data.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(DetectedActivitiesIntentService.this));
Job myJob = dispatcher.newJobBuilder()
.setService(SendCarProbeDataService.class) // the JobService that will be called
.setTag(tripId)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setExtras(bundle)
.build();
dispatcher.mustSchedule(myJob);
I have noticed that my posting service runs after some duration.
When I research on it, I get to know that there is a JobInfo which have the property to set setMinimumLetancy(0) to run the service as quick as possible.
JobInfo jobInfo = new JobInfo.Builder(tripId, SendCarProbeDataService.class)
.setMinimumLatency(0)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setExtras(bundle).build();
But I need to know the difference between Job and JobInfo and how I use setMinimumLetancy in Job?
with job info you can specify the constraints of the job. if you want to execute your job at specific time then use
.setTrigger(Trigger.executionWindow(x, y))
x is the window starting time
y is the window ending time
eg:.setTrigger(Trigger.executionWindow(10, 20))
the job will execute between the time 10 to 20 seconds...
for immediate execution use
.setTrigger(Trigger.NOW)

Firebase Jobdispatcher - Start now AND repeat

Per this example, I see that I can have the job start now using Trigger.NOW or a time of 0,0:
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(false)
// don't persist past a device reboot
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
// only run when the device is charging
Constraint.DEVICE_CHARGING
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
My question is:
How do I set the job to start now but also repeat every [time interval] (lets call it 15 minutes)?
To make your job repeat periodically call these two methods:
.setRecurring(true) //true mean repeat it
.setTrigger(Trigger.executionWindow(start, end))
start : is know as windowStart, which is the earliest time (in seconds) the job should be considered eligible to run. Calculated from when the job was scheduled (for new jobs)
end : is know as windowEnd, The latest time (in seconds) the job should be run in an ideal world. Calculated in the same way as windowStart.

Categories

Resources