Search in sources :

Example 1 with JobManager

use of com.birbit.android.jobqueue.JobManager in project android-priority-jobqueue by yigit.

the class JobManagerTestBase method createJobManager.

protected JobManager createJobManager(Configuration.Builder configurationBuilder) {
    if (createdJobManagers.size() > 0) {
        throw new AssertionError("only 1 job manager per test");
    }
    if (BuildConfig.DEBUG) {
        configurationBuilder.customLogger(collectLogsRule.logger);
    }
    Configuration config = configurationBuilder.inTestMode().id(UUID.randomUUID().toString()).build();
    if (config.getTimer() != mockTimer && !canUseRealTimer()) {
        throw new IllegalArgumentException("must use mock timer");
    }
    final JobManager jobManager = new JobManager(config);
    createdJobManagers.add(jobManager);
    return jobManager;
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) JobManager(com.birbit.android.jobqueue.JobManager)

Example 2 with JobManager

use of com.birbit.android.jobqueue.JobManager in project android-priority-jobqueue by yigit.

the class JobManagerTestBase method createJobManager.

protected JobManager createJobManager() {
    if (createdJobManagers.size() > 0) {
        throw new AssertionError("only 1 job manager per test");
    }
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).timer(mockTimer).inTestMode());
    createdJobManagers.add(jobManager);
    return jobManager;
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) JobManager(com.birbit.android.jobqueue.JobManager)

Example 3 with JobManager

use of com.birbit.android.jobqueue.JobManager in project android-priority-jobqueue by yigit.

the class JobStatusTest method testJobStatus.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Test
public void testJobStatus() throws InterruptedException {
    DummyNetworkUtilWithConnectivityEventSupport networkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
    networkUtil.setNetworkStatus(NetworkUtil.DISCONNECTED, true);
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).networkUtil(networkUtil).timer(mockTimer));
    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().addTags(REQ_NETWORK_TAG)) };
    String[] ids = new String[jobs.length];
    networkRequiringJobIndices.add(2);
    for (int i = 0; i < jobs.length; i++) {
        jobManager.addJob(jobs[i]);
        ids[i] = jobs[i].getId();
        JobStatus expectedStatus = (!networkUtil.isDisconnected() || !networkRequiringJobIndices.contains(i)) ? JobStatus.WAITING_READY : JobStatus.WAITING_NOT_READY;
        assertThat("job should have correct status after being added", jobManager.getJobStatus(ids[i]), is(expectedStatus));
    }
    //create an unknown id, ensure status for that
    boolean exists;
    String unknownId;
    do {
        unknownId = UUID.randomUUID().toString();
        exists = false;
        for (String id : ids) {
            if (unknownId.equals(id)) {
                exists = true;
            }
        }
    } while (exists);
    for (boolean persistent : new boolean[] { true, false }) {
        assertThat("job with unknown id should return as expected", jobManager.getJobStatus(unknownId), is(JobStatus.UNKNOWN));
    }
    final CountDownLatch startLatch = new CountDownLatch(1), endLatch = new CountDownLatch(1);
    final DummyTwoLatchJob twoLatchJob = new DummyTwoLatchJob(new Params(0), startLatch, endLatch);
    jobManager.start();
    jobManager.addJob(twoLatchJob);
    final String jobId = twoLatchJob.getId();
    twoLatchJob.waitTillOnRun();
    final CountDownLatch twoLatchJobDone = new CountDownLatch(1);
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onAfterJobRun(@NonNull Job job, int resultCode) {
            if (job == twoLatchJob && resultCode == RESULT_SUCCEED) {
                jobManager.removeCallback(this);
                twoLatchJobDone.countDown();
            }
        }
    });
    assertThat("job should be in running state", jobManager.getJobStatus(jobId), is(JobStatus.RUNNING));
    //let it run
    startLatch.countDown();
    try {
        //wait till it finishes
        endLatch.await();
    } catch (InterruptedException ignored) {
    }
    twoLatchJobDone.await(1, TimeUnit.MINUTES);
    assertThat("finished job should go to unknown state. id: " + jobId, jobManager.getJobStatus(jobId), 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]), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    networkUtil.setNetworkStatus(NetworkUtil.METERED, true);
    for (Integer i : networkRequiringJobIndices) {
        assertThat("network requiring job should still be ready after network is there", jobManager.getJobStatus(ids[i]), is(JobStatus.WAITING_READY));
    }
    final CountDownLatch networkRequiredLatch = new CountDownLatch(networkRequiringJobIndices.size());
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            if (job.getTags().contains(REQ_NETWORK_TAG)) {
                networkRequiredLatch.countDown();
            }
        }
    });
    jobManager.start();
    networkRequiredLatch.await(1, TimeUnit.MINUTES);
    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]), is(JobStatus.UNKNOWN));
    }
    final long SHORT_SLEEP = 2000;
    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()) };
    String[] delayedIds = new String[delayedJobs.length];
    long start = mockTimer.nanoTime();
    for (int i = 0; i < delayedJobs.length; i++) {
        jobManager.addJob(delayedJobs[i]);
        delayedIds[i] = delayedJobs[i].getId();
    }
    for (int i = 0; i < delayedJobs.length; i++) {
        assertThat("delayed job(" + i + ") should receive not ready status. startMs:" + start, jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    //sleep
    mockTimer.incrementMs(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]), is(JobStatus.WAITING_READY));
        } else {
            assertThat("delayed job should receive not ready status until their time comes", jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
        }
    }
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) Configuration(com.birbit.android.jobqueue.config.Configuration) ArrayList(java.util.ArrayList) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) JobStatus(com.birbit.android.jobqueue.JobStatus) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) Test(org.junit.Test) TargetApi(android.annotation.TargetApi)

Example 4 with JobManager

use of com.birbit.android.jobqueue.JobManager in project android-priority-jobqueue by yigit.

the class LoadFactorTest method testLoadFactor.

@Test
public void testLoadFactor() throws Exception {
    //test adding zillions of jobs from the same group and ensure no more than 1 thread is created
    int maxConsumerCount = 5;
    int minConsumerCount = 2;
    int loadFactor = 5;
    enableDebug();
    JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).maxConsumerCount(maxConsumerCount).minConsumerCount(minConsumerCount).loadFactor(loadFactor).timer(mockTimer));
    final CountDownLatch runLock = new CountDownLatch(1);
    Semaphore semaphore = new Semaphore(maxConsumerCount);
    int totalJobCount = loadFactor * maxConsumerCount * 5;
    List<DummyJob> runningJobs = new ArrayList<DummyJob>(totalJobCount);
    int prevConsumerCount = 0;
    final Semaphore onRunCount = new Semaphore(totalJobCount);
    onRunCount.acquire(totalJobCount);
    for (int i = 0; i < totalJobCount; i++) {
        DummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore) {

            @Override
            public void onRun() throws Throwable {
                onRunCount.release();
                super.onRun();
            }
        };
        runningJobs.add(job);
        jobManager.addJob(job);
        final int wantedConsumers = (int) Math.ceil((i + 1f) / loadFactor);
        final int expectedConsumerCount = Math.max(Math.min(i + 1, minConsumerCount), Math.min(maxConsumerCount, wantedConsumers));
        if (prevConsumerCount != expectedConsumerCount) {
            assertThat("waiting for another job to start", onRunCount.tryAcquire(1, 10, TimeUnit.SECONDS), is(true));
        }
        assertThat("Consumer count should match expected value at " + (i + 1) + " jobs", jobManager.getActiveConsumerCount(), equalTo(expectedConsumerCount));
        prevConsumerCount = expectedConsumerCount;
    }
    //finish all jobs
    waitUntilJobsAreDone(jobManager, runningJobs, new Runnable() {

        @Override
        public void run() {
            runLock.countDown();
        }
    });
    assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) ArrayList(java.util.ArrayList) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) SuppressLint(android.annotation.SuppressLint) Constraint(com.birbit.android.jobqueue.Constraint) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Test(org.junit.Test)

Example 5 with JobManager

use of com.birbit.android.jobqueue.JobManager in project android-priority-jobqueue by yigit.

the class MultiThreadTest method testMultiThreaded.

@Test
public void testMultiThreaded() throws Exception {
    multiThreadedJobCounter = new AtomicInteger(0);
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).loadFactor(3).maxConsumerCount(10));
    int limit = 200;
    ExecutorService executor = new ThreadPoolExecutor(20, 20, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(limit));
    final String cancelTag = "iWillBeCancelled";
    Collection<Future<?>> futures = new LinkedList<Future<?>>();
    for (int i = 0; i < limit; i++) {
        final int id = i;
        futures.add(executor.submit(new Runnable() {

            @Override
            public void run() {
                final boolean persistent = Math.round(Math.random()) % 2 == 0;
                boolean requiresNetwork = Math.round(Math.random()) % 2 == 0;
                int priority = (int) (Math.round(Math.random()) % 10);
                multiThreadedJobCounter.incrementAndGet();
                Params params = new Params(priority).setRequiresNetwork(requiresNetwork).setPersistent(persistent);
                if (Math.random() < .1) {
                    params.addTags(cancelTag);
                }
                jobManager.addJob(new DummyJobForMultiThread(id, params));
            }
        }));
    }
    // wait for some jobs to start
    //noinspection SLEEP_IN_CODE
    Thread.sleep(1000);
    CancelResult cancelResult = jobManager.cancelJobs(TagConstraint.ALL, cancelTag);
    for (int i = 0; i < cancelResult.getCancelledJobs().size(); i++) {
        multiThreadedJobCounter.decrementAndGet();
    }
    for (Future<?> future : futures) {
        future.get();
    }
    Log.d("TAG", "added all jobs");
    //wait until all jobs are added
    //noinspection DIRECT_TIME_ACCESS
    long start = System.nanoTime();
    //20 minutes
    long timeLimit = JobManager.NS_PER_MS * 60000 * 20;
    //noinspection DIRECT_TIME_ACCESS
    while (System.nanoTime() - start < timeLimit && multiThreadedJobCounter.get() != 0) {
        //noinspection SLEEP_IN_CODE
        Thread.sleep(1000);
    }
    MatcherAssert.assertThat("jobmanager count should be 0", jobManager.count(), equalTo(0));
    jobManager.stopAndWaitUntilConsumersAreFinished();
    MatcherAssert.assertThat("multiThreadedJobCounter should be 0", multiThreadedJobCounter.get(), CoreMatchers.is(0));
}
Also used : CancelResult(com.birbit.android.jobqueue.CancelResult) Configuration(com.birbit.android.jobqueue.config.Configuration) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) TagConstraint(com.birbit.android.jobqueue.TagConstraint) RetryConstraint(com.birbit.android.jobqueue.RetryConstraint) LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Test(org.junit.Test)

Aggregations

JobManager (com.birbit.android.jobqueue.JobManager)58 Params (com.birbit.android.jobqueue.Params)47 Test (org.junit.Test)40 DummyJob (com.birbit.android.jobqueue.test.jobs.DummyJob)35 Job (com.birbit.android.jobqueue.Job)26 CountDownLatch (java.util.concurrent.CountDownLatch)26 Configuration (com.birbit.android.jobqueue.config.Configuration)22 CancelResult (com.birbit.android.jobqueue.CancelResult)9 TargetApi (android.annotation.TargetApi)8 RetryConstraint (com.birbit.android.jobqueue.RetryConstraint)8 JobManagerCallbackAdapter (com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter)8 JobHolder (com.birbit.android.jobqueue.JobHolder)6 ArrayList (java.util.ArrayList)6 JobManagerCallback (com.birbit.android.jobqueue.callback.JobManagerCallback)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Semaphore (java.util.concurrent.Semaphore)3 SuppressLint (android.annotation.SuppressLint)2 NonNull (android.support.annotation.NonNull)2 Constraint (com.birbit.android.jobqueue.Constraint)2 TagConstraint (com.birbit.android.jobqueue.TagConstraint)2