I am using JobScheduler to run the job every 15 mins. But It is not working as expected. Here I attached my code.
public class WorkScheduler extends JobService {
private static final String TAG = "Jobschedulerexample";
private boolean jobCanceled = false;
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.d(TAG,"Started at ==> "+ sdf.format(new Date()));
Log.d(TAG,"Job Started");
doBackgroundWork(jobParameters);
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d(TAG, "Job cancelled before completion");
jobCanceled = true;
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Log.d(TAG, "run: " + i);
if (jobCanceled) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Job finished");
Log.d(TAG,"Ended at ==> "+ sdf.format(new Date()));
jobFinished(params, true);
}
}).start();
}
}
My utility class for Job service
public class WorkSchedulerUtility {
private static final int JOB_ID = 123;
private static WorkSchedulerUtility mInstance;
private final int REFRESH_INTERVAL = 15 * 60 * 1000;
private WorkSchedulerUtility(){
}
public static WorkSchedulerUtility getInstance(){
if(mInstance == null){
mInstance = new WorkSchedulerUtility();
}
return mInstance;
}
private static final String TAG = "Jobschedulerexample";
public void scheduleJob(Context context) {
ComponentName componentName = new ComponentName(context, WorkScheduler.class);
/* JobInfo info = new JobInfo.Builder(JOB_ID, componentName)
.setPersisted(true)
.setPeriodic(REFRESH_INTERVAL)
.build();*/
JobInfo info = new JobInfo.Builder(JOB_ID, componentName)
.setPersisted(true)
.setBackoffCriteria(REFRESH_INTERVAL, JobInfo.BACKOFF_POLICY_LINEAR)
.setMinimumLatency(1000 * 6)
.build();
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
public void cancelJob(Context context) {
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(123);
Log.d(TAG, "Job cancelled");
}
}
I planned to run the job for every 15 mins. But it is not start job every 15 mins. I will attach the output.
Started at ==> 15:10:49 Ended at ==> 15:10:59 Started at ==> 15:25:59 Ended at ==> 15:26:09 Started at ==> 15:56:10 Ended at ==> 15:56:20 Started at ==> 16:41:44 Ended at ==> 16:41:54
I don't know why it is not working for every 15 mins. And also I want to start the job at specific time. For example every day at 8o'Clock. How to achive that using JobSceduler.