Priyamal
Priyamal

Reputation: 2969

how to run a job service at a given time

i want to create something like a reminder app which notify user at given times , i want to use job scheduler api to achieve this let's say i want to run the service at 9 am and 12 am what should be added in the following code to achieve this.

public void startJobService(){

    GooglePlayDriver driver = new GooglePlayDriver(this);
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);

    Bundle myExtrasBundle = new Bundle();
    myExtrasBundle.putString("some_key", "some_value");

    Job myJob = dispatcher.newJobBuilder()
            .setService(jobservice.class)
            .setTag("unique-tag")
             .setExtras(myExtrasBundle)
            .build();

    dispatcher.mustSchedule(myJob);

}

//this is the JobService class

public class jobservice extends JobService{

private static final String TAG = "jobservice";

@Override
public boolean onStartJob(JobParameters job) {

    Log.d(TAG, "onStartJob: "+job.getExtras());

    return true;
}

@Override
public boolean onStopJob(JobParameters job) {
    return false;
}
}

Upvotes: 2

Views: 1452

Answers (1)

mspapant
mspapant

Reputation: 2050

Unfortunately it seems that the JobService does not provide this api. Two things you can do:

  • Use Alarm Manager to trigger the job service when you want or
  • Run you job service frequent (let's say once per hour). Then check if the current time is on your desired interval. If yes proceed, if no abort the job.

For example:

final Job job = dispatcher.newJobBuilder()
            .setService(MyService.class)
            .setTag(MyService.class.getName())
            .setRecurring(true)
            .setLifetime(Lifetime.FOREVER)
            .setTrigger(Trigger.executionWindow(HOUR, 2 * HOUR))
            .setReplaceCurrent(false)
            .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
            .build();

And then inside your Job Service:

@Override
public boolean onStartJob(JobParameters job) {
    if (!nowIsInDesiredInterval()) {
        Timber.i("Now is not inside the desired interval. Aborting.");
        return false;
    }
    // else execute your job
    // .....
    return false;
}

Upvotes: 1

Related Questions