0

I am scheduling multiple jobs at once. I need to run multiple jobs one by one with delay between multiple jobs but some of the jobs runs in parallel. How can I schedule them so they run one after another with set delay. Following is the code used in onStart method.

public boolean onStartJob(final JobParameters jobParameters) {
        new Thread() {
            @Override
            public void run() {
                PersistableBundle persistableBundle = jobParameters.getExtras();
                int delay = persistableBundle.getInt("delay");
                Log.d("Time", new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date()));
                if(delay > 0) {
                    try {
                        sleep(delay * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d("EndTime", new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date()));
                //Do Some work
                jobFinished(jobParameters, false);
            }
        }.start();
        return true;
    }

Following is the debug log for test of 5 jobs.

D/Time: 16:43:21
D/Time: 16:43:22
D/Time: 16:43:24
D/EndTime: 16:43:30
D/EndTime: 16:43:31
D/Time: 16:43:31
D/Time: 16:43:31
D/EndTime: 16:43:33
D/EndTime: 16:43:40
D/EndTime: 16:43:40
Ravi Patel
  • 2,136
  • 3
  • 32
  • 48
  • You create a new thread at every job, so they can run in parallel – vincrichaud Mar 29 '18 at 18:52
  • @vincrichaud But according to docs if I return true in onStart job is not considered as finished untill I call jobFinished method. So new job should start after I call jobFinished not before it. – Ravi Patel Mar 30 '18 at 05:12
  • 1
    If you use one thread for all the jobs, they will wait for job finished before starting. But since you create a new thread every time, the jobs don't even know about each others so they start when they want – vincrichaud Mar 30 '18 at 07:07
  • @vincrichaud Thanks that solved this. I show google does this with Firbase JobDispatcher. They used async task so only one thread will be allocated to all jobs. That way they will run one by one and not all at once. https://github.com/firebase/firebase-jobdispatcher-android/blob/master/jobdispatcher/src/main/java/com/firebase/jobdispatcher/SimpleJobService.java – Ravi Patel Mar 31 '18 at 09:12

0 Answers0