student93
student93

Reputation: 307

Run periodic job while a condition is satisfied?

I'm using the following code to make a job run every time there is available internet. What I want in addition is, after the service is triggered (due to available connection) I want that service to continue running g periodically (every 30 seconds) as long as there is internet and then when the connectivity is no longer available, the service should stop and only resume the next time there is internet.

FirebaseJobDispatcher jobDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(MainActivity.this));

                        .setTag("JobService")

                        .setRecurring(true)

                        .setLifetime(Lifetime.FOREVER)
                        .setService(JobService.class)

                        .setTrigger(Trigger.executionWindow(0,10))

                        .setReplaceCurrent(true)
                        .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL);    

                builder.addConstraint(Constraint.ON_UNMETERED_NETWORK);
                jobDispatcher.mustSchedule(builder.build());

I thought of making the JobService itself schedule the next time it is going to run (in thirty seconds) and after the time is up, test if there is internet then ok else I'll call the Onstop method but it didn't feel like the right approach to solve this.

Upvotes: 0

Views: 729

Answers (1)

Dika
Dika

Reputation: 2442

you can write : setTrigger(Trigger.executionWindow(30,40)) . explanation: firebase job dispatcher github

Scheduling a more complex job

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))

or for executionWindow, the rule is:

.setTrigger(Trigger.executionWindow(
                        INTERVAL_IN_SECONDS,
                        INTERVAL_IN_SECONDS + TIME_WINDOW_IN_SECONDS
                ))

reference: https://stackoverflow.com/a/39909986/1537413

Upvotes: 1

Related Questions