0

I did not find anything about this topic, however I am curious what your recommendations or "best practices" are regarding when to set the rules to schedule the task? For example if I have to schedule a sync job, which should always be there as long as the app runs, where would the

new JobRequest.Builder("...")..
  .build()
  .schedule()

be called?

Thank you

thehayro
  • 1,516
  • 2
  • 16
  • 28

2 Answers2

1

You should create JobCreator which will instantiate your Job class like this:

public class MyJobCreator implements JobCreator {

    @Override
    public Job create(String tag) {
        if (MyJob.TAG.equals(tag)) {
            return new MyJob();
        }

        return null;
    }
}

And initialize it in Application.onCreate():

JobManager.create(this).addJobCreator(new MyJobCreator());
MyJob.scheduleJob();

MyJob may look like this:

public class MyJob extends Job {

    public static final String TAG = "my_job_tag";

    @Override
    @NonNull
    protected Result onRunJob(Params params) {
        Intent i = new Intent(getContext(), MyService.class);
        getContext().startService(i);
        return Result.SUCCESS;
    }

    public static void scheduleJob() {
        new JobRequest.Builder(MyJob.TAG)
                .setPeriodic(60_000L) // 1 minute
                .setRequiredNetworkType(JobRequest.NetworkType.ANY)
                .setPersisted(true)
                .setUpdateCurrent(true)
                .setRequirementsEnforced(true)
                .build()
                .schedule();
    }
}
shmakova
  • 6,076
  • 3
  • 28
  • 44
1

Extending shmakova's answer, you may need to add a condition if your sync job is already scheduled like this:

public static void scheduleJob() {
    if (JobManager.instance().getAllJobRequestsForTag(MyJob.TAG).isEmpty()) {
        new JobRequest.Builder(MyJob.TAG)
                .setPeriodic(900_000L)
                .setRequiredNetworkType(JobRequest.NetworkType.ANY)
                .setPersisted(true)
                .setUpdateCurrent(true)
                .setRequirementsEnforced(true)
                .build()
                .schedule();
    }
}

this will prevent scheduling multiple jobs

rehman_00001
  • 1,299
  • 1
  • 15
  • 28