I'm new to the JobDispatcher and so I'm not pretty sure whether my question makes sense or not.
I have a requirement where I need to run some tasks periodically in the background (even if the App is not running). The task is not executing in a fixed time interval. On executing task for the first time , I'll get to know the schedule of the next task execution, So after the first execution, I should re-schedule the same task to a next time in future, which I will get to know after completing the task. And it goes on like this.
Its like syncing something from network , and the network data will tell when to sync next.
So, My questions are
Should I create a new Job each time for each new task?
Can I create repeating job and keep on changing the interval?
How can I deal with this scenario exactly with FireBaseJobDispatcher.
I chose FireBaseJobDispatcher over JobScheduler because my App has to support below Lollipop also.
Here is a sample code I tried with FireBaseJobDispatcher with executing a task at a given time, and its working fine. Now I'm stuck how to re-schedule it to the next syncing time.
public class MyJobService extends JobService {
private static final String TAG = "MyJobService";
@Override
public boolean onStartJob(final JobParameters job) {
// Do some work here
Log.d(TAG, "onStartJob: at "+Thread.currentThread().getName());
new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: startign job ");
try {
Thread.sleep(2000);
// some syncing operation
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "run: job done");
// here I need to reschedule the same job to a future time
}
}).start();
return false;
}
@Override
public boolean onStopJob(JobParameters job) {
Log.d(TAG, "onStopJob: ");
return false;
}
}
I'm setting the Job in the activity like this
// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("syncservice")
.setRecurring(true)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(1*60*60 , 1*60*60)) // rigger after an hour
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setConstraints(
Constraint.ON_ANY_NETWORK
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
Thanks In advance!