Search in sources :

Example 11 with Params

use of com.path.android.jobqueue.Params in project android-priority-jobqueue by path.

the class DelayTest method testDelay.

public void testDelay(boolean persist) throws Exception {
    JobManager jobManager = createJobManager();
    jobManager.stop();
    DummyJob delayedJob = new DummyJob(new Params(10).delayInMs(1000).setPersistent(persist));
    DummyJob nonDelayedJob = new DummyJob(new Params(0).setPersistent(persist));
    long jobId = jobManager.addJob(delayedJob);
    long nonDelayedJobId = jobManager.addJob(nonDelayedJob);
    Invoker<JobHolder> nextJobMethod = getNextJobMethod(jobManager);
    Invoker<Void> removeJobMethod = getRemoveJobMethod(jobManager);
    JobHolder receivedJob = nextJobMethod.invoke();
    MatcherAssert.assertThat("non-delayed job should be served", receivedJob, notNullValue());
    MatcherAssert.assertThat("non-delayed job should id should match", receivedJob.getId(), equalTo(nonDelayedJobId));
    removeJobMethod.invoke(receivedJob);
    MatcherAssert.assertThat("delayed job should not be served", nextJobMethod.invoke(), nullValue());
    MatcherAssert.assertThat("job count should still be 1", jobManager.count(), equalTo(1));
    Thread.sleep(500);
    MatcherAssert.assertThat("delayed job should not be served", nextJobMethod.invoke(), nullValue());
    MatcherAssert.assertThat("job count should still be 1", jobManager.count(), equalTo(1));
    Thread.sleep(2000);
    MatcherAssert.assertThat("job count should still be 1", jobManager.count(), equalTo(1));
    receivedJob = nextJobMethod.invoke();
    MatcherAssert.assertThat("now should be able to receive the delayed job.", receivedJob, notNullValue());
    if (receivedJob != null) {
        MatcherAssert.assertThat("received job should be the delayed job", receivedJob.getId(), equalTo(jobId));
    }
}
Also used : JobHolder(com.path.android.jobqueue.JobHolder) DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) Params(com.path.android.jobqueue.Params) JobManager(com.path.android.jobqueue.JobManager)

Example 12 with Params

use of com.path.android.jobqueue.Params in project android-priority-jobqueue by path.

the class DelayedRunTest method testDelayedRun.

public void testDelayedRun(boolean persist, boolean tryToStop) throws Exception {
    JobManager jobManager = createJobManager();
    DummyJob delayedJob = new DummyJob(new Params(10).delayInMs(2000).setPersistent(persist));
    DummyJob nonDelayedJob = new DummyJob(new Params(0).setPersistent(persist));
    jobManager.addJob(delayedJob);
    jobManager.addJob(nonDelayedJob);
    Thread.sleep(500);
    MatcherAssert.assertThat("there should be 1 delayed job waiting to be run", jobManager.count(), equalTo(1));
    if (tryToStop) {
        // see issue #11
        jobManager.stop();
        Thread.sleep(3000);
        MatcherAssert.assertThat("there should still be 1 delayed job waiting to be run when job manager is stopped", jobManager.count(), equalTo(1));
        jobManager.start();
    }
    Thread.sleep(3000);
    MatcherAssert.assertThat("all jobs should be completed", jobManager.count(), equalTo(0));
}
Also used : DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) Params(com.path.android.jobqueue.Params) JobManager(com.path.android.jobqueue.JobManager)

Example 13 with Params

use of com.path.android.jobqueue.Params in project android-priority-jobqueue by path.

the class GroupingTest method testGroupingRaceCondition.

@Test
public void testGroupingRaceCondition() throws Exception {
    DummyNetworkUtilWithConnectivityEventSupport dummyNetworkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
    JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).minConsumerCount(5).maxConsumerCount(10).networkUtil(dummyNetworkUtil));
    dummyNetworkUtil.setHasNetwork(false, true);
    // add a bunch of network requring jobs
    final String GROUP_ID = "shared_group_id";
    final int AFTER_ADDED_JOBS_COUNT = 5;
    final int NOT_SET_JOB_ID = -1;
    final AtomicInteger firstRunJob = new AtomicInteger(NOT_SET_JOB_ID);
    final int FIRST_JOB_ID = -10;
    final CountDownLatch onAddedCalled = new CountDownLatch(1);
    final CountDownLatch remainingJobsOnAddedCalled = new CountDownLatch(AFTER_ADDED_JOBS_COUNT);
    jobManager.addJobInBackground(new DummyJob(new Params(10).requireNetwork().groupBy(GROUP_ID)) {

        @Override
        public void onAdded() {
            super.onAdded();
            onAddedCalled.countDown();
            try {
                // wait until all other jobs are added
                remainingJobsOnAddedCalled.await();
                // wait a bit after all are added,
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }

        @Override
        public void onRun() throws Throwable {
            super.onRun();
            firstRunJob.compareAndSet(NOT_SET_JOB_ID, FIRST_JOB_ID);
        }
    });
    // ensure first jobs on added is called
    onAddedCalled.await();
    for (int i = 0; i < AFTER_ADDED_JOBS_COUNT; i++) {
        final int finalI = i;
        jobManager.addJob(new DummyJob(new Params(5).groupBy(GROUP_ID).requireNetwork()) {

            final int id = finalI + 1;

            @Override
            public void onAdded() {
                super.onAdded();
                remainingJobsOnAddedCalled.countDown();
            }

            @Override
            public void onRun() throws Throwable {
                super.onRun();
                firstRunJob.compareAndSet(NOT_SET_JOB_ID, id);
            }
        });
    }
    dummyNetworkUtil.setHasNetwork(true, true);
    // wait until all jobs are completed
    while (firstRunJob.get() == NOT_SET_JOB_ID) {
        Thread.sleep(100);
    }
    MatcherAssert.assertThat("highest priority job should run if it is added before others", firstRunJob.get(), is(FIRST_JOB_ID));
}
Also used : DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Params(com.path.android.jobqueue.Params) JobManager(com.path.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 14 with Params

use of com.path.android.jobqueue.Params in project android-priority-jobqueue by path.

the class InjectorTest method testInjectorCrash.

@Test
public void testInjectorCrash() throws Exception {
    final String EXCEPTION_MESSAGE = "could not inject for whatever reason :)";
    DependencyInjector dummyDependencyInjector = new DependencyInjector() {

        @Override
        public void inject(BaseJob baseJob) {
            throw new RuntimeException(EXCEPTION_MESSAGE);
        }
    };
    final ObjectReference objectReference = new ObjectReference();
    final CountDownLatch exceptionLatch = new CountDownLatch(1);
    CustomLogger customLogger = new CustomLogger() {

        @Override
        public boolean isDebugEnabled() {
            return false;
        }

        @Override
        public void d(String s, Object... objects) {
        }

        @Override
        public void e(Throwable throwable, String s, Object... objects) {
            objectReference.setObject(throwable);
            exceptionLatch.countDown();
        }

        @Override
        public void e(String s, Object... objects) {
        // 
        }
    };
    JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).injector(dummyDependencyInjector).customLogger(customLogger));
    Throwable addException = null;
    try {
        jobManager.addJob(new DummyJob(new Params(0)));
    } catch (Throwable t) {
        addException = t;
    }
    MatcherAssert.assertThat("addJob should throw exception if dependency injector throws exception", addException, notNullValue());
    jobManager.addJobInBackground(new DummyJob(new Params(0)));
    exceptionLatch.await(2, TimeUnit.SECONDS);
    MatcherAssert.assertThat("there should be a received exception", objectReference.getObject(), notNullValue());
    MatcherAssert.assertThat("logged exception should be a runtime exception", objectReference.getObject(), instanceOf(RuntimeException.class));
    MatcherAssert.assertThat("logged exception should have expected message", ((Throwable) objectReference.getObject()).getMessage(), is(EXCEPTION_MESSAGE));
}
Also used : DependencyInjector(com.path.android.jobqueue.di.DependencyInjector) Configuration(com.path.android.jobqueue.config.Configuration) BaseJob(com.path.android.jobqueue.BaseJob) Params(com.path.android.jobqueue.Params) CustomLogger(com.path.android.jobqueue.log.CustomLogger) JobManager(com.path.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) Test(org.junit.Test)

Example 15 with Params

use of com.path.android.jobqueue.Params in project android-priority-jobqueue by path.

the class JobStatusTest method testJobStatus.

@Test
public void testJobStatus() throws InterruptedException {
    DummyNetworkUtilWithConnectivityEventSupport networkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
    networkUtil.setHasNetwork(false, true);
    JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).networkUtil(networkUtil));
    jobManager.stop();
    List<Integer> networkRequiringJobIndices = new ArrayList<Integer>();
    Job[] jobs = new Job[] { new DummyJob(new Params(0)), new DummyJob(new Params(0).persist()), new DummyJob(new Params(0).persist().requireNetwork()) };
    long[] ids = new long[jobs.length];
    for (int i = 0; i < jobs.length; i++) {
        ids[i] = jobManager.addJob(jobs[i]);
        if (jobs[i].requiresNetwork()) {
            networkRequiringJobIndices.add(i);
        }
        JobStatus expectedStatus = (networkUtil.isConnected() || jobs[i].requiresNetwork() == false) ? JobStatus.WAITING_READY : JobStatus.WAITING_NOT_READY;
        assertThat("job should have correct status after being added", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(expectedStatus));
    }
    // create an unknown id, ensure status for that
    boolean exists;
    long unknownId;
    do {
        unknownId = (long) (Math.random() * 10000 - 5000);
        exists = false;
        for (long id : ids) {
            if (id == unknownId) {
                exists = true;
                continue;
            }
        }
    } while (exists);
    for (boolean persistent : new boolean[] { true, false }) {
        assertThat("job with unknown id should return as expected", jobManager.getJobStatus(unknownId, persistent), is(JobStatus.UNKNOWN));
    }
    CountDownLatch startLatch = new CountDownLatch(1), endLatch = new CountDownLatch(1);
    DummyTwoLatchJob twoLatchJob = new DummyTwoLatchJob(new Params(0), startLatch, endLatch);
    jobManager.start();
    long jobId = jobManager.addJob(twoLatchJob);
    twoLatchJob.waitTillOnRun();
    assertThat("job should be in running state", jobManager.getJobStatus(jobId, false), is(JobStatus.RUNNING));
    // let it run
    startLatch.countDown();
    // wait till it finishes
    endLatch.await();
    // give some time to job manager to clear the job
    Thread.sleep(500);
    assertThat("finished job should go to unknown state", jobManager.getJobStatus(jobId, false), is(JobStatus.UNKNOWN));
    // network requiring job should not be ready
    for (Integer i : networkRequiringJobIndices) {
        assertThat("network requiring job should still be not-ready", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    networkUtil.setHasNetwork(true, true);
    for (Integer i : networkRequiringJobIndices) {
        assertThat("network requiring job should still be ready after network is there", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.WAITING_READY));
    }
    jobManager.start();
    int limit = 10;
    while (jobManager.count() > 0 && limit-- > 0) {
        Thread.sleep(1000);
    }
    assertThat("jobs should finish", jobManager.count(), is(0));
    for (int i = 0; i < jobs.length; i++) {
        // after all jobs finish, state should be unknown
        assertThat("all jobs finished, states should be unknown", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.UNKNOWN));
    }
    final long SHORT_SLEEP = 1000;
    Job[] delayedJobs = new Job[] { new DummyJob(new Params(0).delayInMs(SHORT_SLEEP)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP).persist()), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10).persist()) };
    long[] delayedIds = new long[delayedJobs.length];
    for (int i = 0; i < delayedJobs.length; i++) {
        delayedIds[i] = jobManager.addJob(delayedJobs[i]);
    }
    for (int i = 0; i < delayedJobs.length; i++) {
        assertThat("delayed job(" + i + ") should receive not ready status", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    // sleep
    Thread.sleep(SHORT_SLEEP * 2);
    for (int i = 0; i < delayedJobs.length; i++) {
        if (delayedJobs[i].getDelayInMs() == SHORT_SLEEP) {
            assertThat("when enough time passes, delayed jobs should move to ready state", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_READY));
        } else {
            assertThat("delayed job should receive not ready status until their time comes", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Params(com.path.android.jobqueue.Params) JobManager(com.path.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) JobStatus(com.path.android.jobqueue.JobStatus) DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) DummyJob(com.path.android.jobqueue.test.jobs.DummyJob) Job(com.path.android.jobqueue.Job) Test(org.junit.Test)

Aggregations

Params (com.path.android.jobqueue.Params)36 Test (org.junit.Test)33 DummyJob (com.path.android.jobqueue.test.jobs.DummyJob)22 JobManager (com.path.android.jobqueue.JobManager)20 JobHolder (com.path.android.jobqueue.JobHolder)17 JobQueue (com.path.android.jobqueue.JobQueue)13 CountDownLatch (java.util.concurrent.CountDownLatch)8 Configuration (com.path.android.jobqueue.config.Configuration)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 BaseJob (com.path.android.jobqueue.BaseJob)4 Job (com.path.android.jobqueue.Job)3 ArrayList (java.util.ArrayList)3 DependencyInjector (com.path.android.jobqueue.di.DependencyInjector)2 CustomLogger (com.path.android.jobqueue.log.CustomLogger)2 Semaphore (java.util.concurrent.Semaphore)2 AsyncAddCallback (com.path.android.jobqueue.AsyncAddCallback)1 JobStatus (com.path.android.jobqueue.JobStatus)1 JobConsumerExecutor (com.path.android.jobqueue.executor.JobConsumerExecutor)1 SqliteJobQueue (com.path.android.jobqueue.persistentQueue.sqlite.SqliteJobQueue)1 LinkedList (java.util.LinkedList)1