Can i use Firebase JobDispatcher for triggering time specific tasks - android

I am developing an application where certain tasks as to be done in background at a specific time.
Android developer docs suggests various methods. I know AlarmManager can be used for this purpose. But, I think, using AlarmManager in Android 6.0 in Doze mode will give improper triggers.
I came across JobScheduling libraries from developer docs
As my application supports version below Android 5.0. I thought of using FireBaseJobDispatcher.
Can I use FirebaseJobDispatcher for trigger a specific task at a specific time.
For Example : I want to update the DB once every hour from 9AM to 6PM

You can, but if you time window is not so strict, there is no guarantee that your task start to work in a few hours later, because Doze mode. If you want really strict scheduling - use AlarmManager.setAndAllowWhileIdle.
And, as I know FirebaseJobDispatcher has not released yet, and there is a few unresolved issues. Before it releases, you can use GCMNetworkManager (from Google Play Services com.google.android.gms:play-services-gcm) for this purpose.
Your code for FirebaseJobDispatcher may looks like this:
final FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
if (isSyncEnabled) {
Job job = dispatcher.newJobBuilder()
.setService(SyncService.class)
.setTag(TAG)
.setConstraints(isSyncOnlyWiFi ? Constraint.ON_UNMETERED_NETWORK : Constraint.ON_ANY_NETWORK)
.setRecurring(true) // !!!
.setLifetime(Lifetime.FOREVER) //!!!
.setTrigger(Trigger.executionWindow(syncIntervalInSeconds, syncIntervalInSeconds + TIME_WINDOW_IN_SECONDS))
.setReplaceCurrent(true)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.build();
final int result = dispatcher.schedule(job);
if (result != FirebaseJobDispatcher.SCHEDULE_RESULT_SUCCESS) {
// pre handle error
}
For GcmNetworkManager:
PeriodicTask task = new PeriodicTask.Builder()
.setService(SyncManagerService.class)
.setTag(TASK_TAG_SYNC_SERVICE)
.setUpdateCurrent(true)
.setPersisted(true)
.setPeriod(period)
.setFlex(flexInSeconds < period ? flexInSeconds : period)
.setRequiredNetwork(wifiOnly ? PeriodicTask.NETWORK_STATE_UNMETERED : PeriodicTask.NETWORK_STATE_CONNECTED)
.build();
GcmNetworkManager.getInstance(context).schedule(task);

Related

Android WorkManager doesn't trigger one of the two scheduled workers

I have two periodic workers scheduled in my app where one worker repeats after 24 hours and another in 15 minutes.
Initially on fresh install things work as expected, but after some days I got an issue on 2 devices(out of 5).
The 24 hour worker is triggered properly but the 15 minute one isn't triggered at all. I have been monitoring this for 24 hours now.
I viewed the databse of workmanager via Stetho and saw some entries for 24-hour worker and 0 entries for 15 minute worker. I'm looking in the WorkSpec table.
I debugged via Android studio and after querying WorkManager using getWorkInfosByTag() I got a list of 80 objects for the 15-minute worker where 79 were in CANCELED state and one was in ENQUEUED state.
So apparently, canceled workers are not added to the DB?
I did not find any document from Google which explains the scenarios in which worker is canceled.
I am using 1.0.0-beta03 version of the work runtime.
Also, I am not killing the app or doing anything funny. The app is running in the background and not being killed.
Devices are Mi A2 (Android 9), Redmi Note 4(Android 7).
I need to understand why is the worker being canceled and is there any better way to debug this? Any pointers will be helpful and upvoted!
Thanks.
Edit1: Posting the code to schedule both workers.
24-hour periodic worker:
public static synchronized void scheduleWork() {
checkPreviousWorkerStatus();
if (isWorking()) {
Log.i("AppDataCleanupWorker", "Did not schedule data cleanup work; already running.");
return;
}
if (lastWorkId != null) {
WorkManager.getInstance().cancelAllWorkByTag("AppDataCleanupWorker");
lastWorkId = null;
}
Constraints constraints = new Constraints.Builder()
.setRequiresCharging(true)
.build();
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest
.Builder(AppDataCleanupWorker.class, 24, TimeUnit.HOURS)
.addTag("AppDataCleanupWorker")
.setConstraints(constraints);
PeriodicWorkRequest workRequest = builder.build();
lastWorkId = workRequest.getId();
WorkManager.getInstance().enqueue(workRequest);
List<WorkInfo> workInfos = WorkManager.getInstance()
.getWorkInfosByTagLiveData("AppDataCleanupWorker")
.getValue();
if (workInfos != null && workInfos.size() > 1) {
throw new RuntimeException("Multiple workers scheduled. Only one schedule is expected.");
}
}
15-minute periodic worker:
public static synchronized void scheduleWork() {
checkPreviousWorkerStatus();
if (isWorking) {
Log.i("ImageUploadWorker", "Did not schedule image upload work; already running.");
return;
}
if (lastWorkId != null) {
WorkManager.getInstance().cancelAllWorkByTag("ImageUploadWorker");
lastWorkId = null;
}
Constraints constraints = new Constraints.Builder()
.setRequiresBatteryNotLow(true)
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
PeriodicWorkRequest.Builder builder =
new PeriodicWorkRequest.Builder(ImageUploadWorker.class, 15,
TimeUnit.MINUTES)
.addTag("ImageUploadWorker")
.setConstraints(constraints);
PeriodicWorkRequest workRequest = builder.build();
lastWorkId = workRequest.getId();
WorkManager.getInstance().enqueue(workRequest);
List<WorkInfo> workInfos = WorkManager.getInstance()
.getWorkInfosByTagLiveData("ImageUploadWorker").getValue();
if (workInfos != null && workInfos.size() > 1) {
throw new RuntimeException("Multiple workers scheduled. Only one schedule is expected.");
}
}
Note: The device is connected to the Internet & network speed is pretty good.
SOLVED: Worker not being triggered by WorkManager
Resolved the issue after some debugging. Posting here in case someone runs into the same issue.
So, I was canceling and enqueuing workers again and again. So lets say a worker is scheduled for 11.15 AM today, then I cancel and enqueue again, the 11.15 AM slot was not being given to the newly enqueued worker.
Instead, When the 11.15 AM slot is utilised, the work manager just checks that the scheduled worker was canceled and does not trigger the newly enqueued worker.
This was the behaviour on 3 out of 5 devices we tested on. On 2 devices the newly enqueued worker was properly being triggered.
Now the solution:
Remove all code to schedule your workers.
In the onCreate() of your application, first invoke pruneWork() on WorkManager to remove all piled up cancelled worker schedules. Remember the method returns Operation which will help you check the completion of removal.
Before calling pruneWork() you might also call cancelAllWorkByTag() for all your workers to clean up any and all the pending schedules. This method also returns an Operation.
After the work manager schedules are cleared, you can now schedule your PeriodicWorkRequest the way you want. I used enqueueUniquePeriodicWork() to make sure only one instance of worker is running at a time.
Now, my worker is being triggered every 15 minutes properly.
Note that as and when your device sleeps and goes into doze mode, this 15 minute duration will increase.
You can check the work manager database using Stetho library.
The table name is WorkSpec where you'll find all the schedules for your workers. And you can stop app execution at some breakpoint and use getWorkInfosByTag() on WorkManager to get a list of schedules and their current status.
You're doing a few things that are incorrect.
You're using LiveData and calling getValue() on it without adding an Observer. This won't give you what you're looking for - the LiveData never starts tracking the values that you want. Please check out proper LiveData usage here: https://developer.android.com/topic/libraries/architecture/livedata
If you only want one particular copy of a type of work, you should use enqueueUniqueWork instead of enqueue.
Unless you found yourself in an extremely bad situation where you actually need to remove old workers, I would advise you not to call pruneWork(). Please see the documentation: https://developer.android.com/reference/androidx/work/WorkManager#pruneWork()

How to run service every 30 mins forever using Firebase JobDispatcher?

Till now, I have used AlarmManager to send HTTP request every 30 minutes. But recently, I faced warning in Google Play Console: Excessive Wakeups. When I read warning details, it said that AlarmManager waking devices up excessively.
Then I researched on what else I could use to send request every 30 minutes. In result, I found this documentation. It recommends to use JobScheduler or JobDispatcher. First of all, I tried to use JobScheduler - but it required API 21 which is not okey for me. I need to support devices from API 16 in my current project. Then I decided to use JobDispatcher.
This is my JobService:
public class MyJobService extends JobService {
#Override
public boolean onStartJob(final JobParameters params) {
Log.d("JobDispatcherLog", params.getTag()+ " STARTED");
jobFinished(params, true);
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d("JobDispatcherLog", params.getTag()+ " STOPPED");
return false;
}
}
This is where I am creating job which is supposed to run service every 30 minutes.
FirebaseJobDispatcher dispatcher =
new FirebaseJobDispatcher(new GooglePlayDriver(this));
RetryStrategy retryStrategy =
dispatcher.newRetryStrategy(
RetryStrategy.RETRY_POLICY_LINEAR, 1800, 86400);
Job job = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("very-important-job")
.setLifetime(Lifetime.FOREVER)
.setReplaceCurrent(true)
.setRetryStrategy(retryStrategy)
.setConstraints(Constraint.ON_ANY_NETWORK)
.build();
dispatcher.mustSchedule(job);
I tested this code and got following result in LogCat:
03-16 18:01:08.540 D/JobDispatcherLog: very-important-job STARTED
03-16 18:43:41.747 D/JobDispatcherLog: very-important-job STARTED
03-16 20:12:01.361 D/JobDispatcherLog: very-important-job STARTED
As you can see it is not running every 30 minutes.
My question: Is this normal behaviour for JobDispatcher? How to run service exactly every 30 minutes? If it is not possible, what else I can use to implement before stated function?
You can reduce the time window in which your job could be triggered. It can help you to control a little the time margin in which your job must trigger.
// Create a new FirebaseJobDispatcher with the driver
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
// Building the Job.
Job yourJob = dispatcher.newJobBuilder()
.setService(YourJobService.class) // The Job service that will execute.
.setTag(YOUR_JOB_TAG) // Unique Tag.
.setLifetime(Lifetime.FOREVER) // To make it last "forever".
.setRecurring(true) // To make it repetitive
/* setTrigger is your time window. You can adjust the SYNC_FLEXTIME_SECONDS to reduce the window a little. But it is not guaranteed to be .*/
.setTrigger(Trigger.executionWindow(ALARM_INTERVAL_SECONDS, ALARM_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS))
.setReplaceCurrent(true) // To make it to overwrite a previous job created with the same tag.
.build();
NOTE: Be aware that if your are going to use FirejobDispatcher (or JobScheduler) then there will not be guarantees that your service will trigger exactly each 30 min.
If you want a more precise "alarm" then you must incline in using AlarmManager + Foreground Service. Be aware that AlarmManager for Android 6 or later will have a little delay (in other words the alarm will not trigger in exactly 30 minutes).

Is it possible to re-schedule job within your job

I'm using Evernote's JobScheduler. The library provides a way to set a periodic job, however that has a minimum interval of 15 minutes between repetitions.
I want to be able to send a user's location to the server every few minutes (maximum 3, minimum 2). Is it technically OK to schedule your old job again and again after the job is done? Something like this:
protected Result onRunJob(Params params)
{
// my actual job runs here
schedulePeriodicJob();
return Result.SUCCESS;
}
private void schedulePeriodicJob()
{
jobId = new JobRequest.Builder(ScheduleJob.TAG)
.setExact(TimeUnit.MINUTES.toMillis(2))
.setBackoffCriteria(TimeUnit.MINUTES.toMillis(1), JobRequest.BackoffPolicy.LINEAR)
.build()
.schedule();
}
Or should I simply use a foreground service to achieve this?
Evernote job scheduler is based upon JobScheduler, GcmNetworkManager or AlarmManager depending on the context/device/playservices version. Whatever the implementation, APIs exposes the following method:
public JobRequest.Builder setPeriodic(long intervalMs, long flexMs)
I would use this one instead of "manually" rescheduling job. I also don't think your setBackoffCriteria call would not work without setting recurring job at APIs level.

Schedule recurring job using firebase job dispatcher

I am trying to post the location of the android device to server every 10 minutes. I am using firebase job dispatcher to do this
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(UpdateLocationService.class)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(10, 20))
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
.setTag("location-update-job")
.setLifetime(Lifetime.FOREVER)
.build();
dispatcher.mustSchedule(myJob);
UpdateLocationService gets the location and sends to server.
My problem: Things are mostly working fine. Only thing is, the jobs are getting scheduled with a difference of 4m, 6m, 7m, 8m, 10m, 16m, 23m...
Can some one please help me understand going on.
Update: I want the location once in 10-20 minutes. In the above code, the value is too low just for the testing purposes
Also the:
Trigger.executionWindow(windowStart, windowEnd)
expects the windowStart and windowEnd in seconds. As per your requirement, you want the window to be 10 mins. So you should use something like:
Trigger.executionWindow(10*60, 20*60)
There are a few reasons why this could be happening. Firstly is your job returning false in onStopJob()? From the docs
#Override
public boolean onStopJob(JobParameters job) {
return false; // Answers the question: "Should this job be retried?"
}
If the job needs be retried then the backoff will be applied. Combine this with the fact you want it to run again every 10-20 seconds you might get the results you are experiencing.
You have not set any constraints for the job, which also will affect when it will run. e.g.
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
// only run when the device is charging
Constraint.DEVICE_CHARGING
)
Furthermore, I would not use a scheduled job for what you are doing. Look at the Google API Client which offers periodic updates from the fused location provider.
You can implement a callback on your Service or Activity like so
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
...
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(mLastUpdateTime);
}
}
Checkout the full docs here but I believe you will have a more consistent experience with services dedicated to what you are trying to achieve.
https://developer.android.com/training/location/receive-location-updates.html
ExecutionWindow specifies approximate time. It's not guaranteed that job will run at the given window. If it misses the window the job will run at earliest time later under ideal circumstances.For recurring jobs once the job has finished next job will calculate execution window time from the time job last run.
LINK
ExecutionWindow represents a Job trigger that becomes eligible once
the current elapsed time exceeds the scheduled time + the {#code windowStart}
value. The scheduler backend is encouraged to use the windowEnd value as a
signal that the job should be run, but this is not an enforced behavior.

job scheduler in android N with less then 15 minutes interval

Part of my question, how I can set up a job with less then 15 minutes interval in "Nougat", was answerd by "blizzard" in his answer here:
Job Scheduler not running on Android N
He explained the problem and suggested to use the following workaround:
JobInfo jobInfo;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
.setMinimumLatency(REFRESH_INTERVAL)
.setExtras(bundle).build();
} else {
jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
.setPeriodic(REFRESH_INTERVAL)
.setExtras(bundle).build();
}
However, using the suggested
.setMinimumLatency(REFRESH_INTERVAL)
just starts the job once;
but how do I get it periodic with a period of around 30 seconds on an android nougat device (not using handler or alarm manager)?
If someone is still trying to overcome the situation,
Here is a workaround for >= Android N (If you want to set the periodic job lower than 15 minutes)
Check that only setMinimumLatency is used. Also, If you are running a task that takes a long time, the next job will be scheduled at, Current JOB Finish time + PROVIDED_TIME_INTERVAL
.SetPeriodic(long millis) works well for API Level below Android N
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d(TAG,"Running service now..");
//Small or Long Running task with callback
//Reschedule the Service before calling job finished
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
scheduleRefresh();
//Call Job Finished
jobFinished(jobParameters, false );
return true;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
private void scheduleRefresh() {
JobScheduler mJobScheduler = (JobScheduler)getApplicationContext()
.getSystemService(JOB_SCHEDULER_SERVICE);
JobInfo.Builder mJobBuilder =
new JobInfo.Builder(YOUR_JOB_ID,
new ComponentName(getPackageName(),
GetSessionService.class.getName()));
/* For Android N and Upper Versions */
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mJobBuilder
.setMinimumLatency(60*1000) //YOUR_TIME_INTERVAL
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
}
UPDATE:
If you are considering your repeating job to run while in Doze Mode and thinking about JobScheduler, FYI: JobSchedulers are not allowed to run in Doze mode.
I have not discussed about the Dozing because we were talking about JobScheduler. Thanks, #Elletlar, for pointing out that some may think that it will run even when the app is in doze mode which is not the case.
For doze mode, AlarmManager still gives the best solution. You can use setExactAndAllowWhileIdle() if you want to run your periodic job at exact time period or use setAndAllowWhileIdle() if you're flexible.
You can also user setAlarmClock() as device always comes out from doze mode for alarm clock and returns to doze mode again. Another way is to use FCM.
Reference: Doze Restrictions
https://developer.android.com/training/monitoring-device-state/doze-standby
I struggled with same thing when I wanted to setup Job for refresh small part of data. I found out that solution for this problem may be setting up Job one more time with the same ID after i calledjobFinished(JobParameters, boolean). I think it should work every time on main thread.
My function to setup Job looks like this:
JobInfo generateRefreshTokenJobInfo(long periodTime){
JobInfo.Builder jobBuilder = new JobInfo.Builder(1L, new ComponentName(mContext, JobService.class));
jobBuilder.setMinimumLatency(periodTime);
jobBuilder.setOverrideDeadline((long)(periodTime * 1.05));
jobBuilder.setRequiresDeviceIdle(false);
return jobBuilder.build();
}
When I finish my work after first call of Job i call in main thread
jobFinished(mJobParameters, true);
registerRefreshJob(5*60*1000L);
This will reschedule my Job one more time for the same amount of time on the same id. When device is in idle state you still have to take under consideration lack of wake locks in doze so your job may not be started so often as you wish. It is mentioned in https://developer.android.com/about/versions/nougat/android-7.0-changes.html
If the device is stationary for a certain time after entering Doze, the system applies the rest of the Doze restrictions to PowerManager.WakeLock, AlarmManager alarms, GPS, and Wi-Fi scans. Regardless of whether some or all Doze restrictions are being applied, the system wakes the device for brief maintenance windows, during which applications are allowed network access and can execute any deferred jobs/syncs.

Categories

Resources