Search in sources :

Example 26 with JobManager

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

the class CleanupRule method finished.

@Override
protected void finished(Description description) {
    String id = getId(description);
    System.out.println("tear down " + id);
    for (JobManager jobManager : test.getCreatedJobManagers()) {
        JobManagerTestBase.NeverEndingDummyJob.unlockAll();
        jobManager.destroy();
    }
    System.out.println("finished tear down of " + id);
}
Also used : JobManager(com.birbit.android.jobqueue.JobManager)

Example 27 with JobManager

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

the class TwitterApplication method configureJobManager.

private void configureJobManager() {
    Configuration.Builder builder = new Configuration.Builder(this).customLogger(new CustomLogger() {

        private static final String TAG = "JOBS";

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

        @Override
        public void d(String text, Object... args) {
            Log.d(TAG, String.format(text, args));
        }

        @Override
        public void e(Throwable t, String text, Object... args) {
            Log.e(TAG, String.format(text, args), t);
        }

        @Override
        public void e(String text, Object... args) {
            Log.e(TAG, String.format(text, args));
        }

        @Override
        public void v(String text, Object... args) {
        }
    }).minConsumerCount(//always keep at least one consumer alive
    1).maxConsumerCount(//up to 3 consumers at a time
    3).loadFactor(//3 jobs per consumer
    3).consumerKeepAlive(//wait 2 minute
    120);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.scheduler(FrameworkJobSchedulerService.createSchedulerFor(this, MyJobService.class), true);
    } else {
        int enableGcm = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
        if (enableGcm == ConnectionResult.SUCCESS) {
            builder.scheduler(GcmJobSchedulerService.createSchedulerFor(this, MyGcmJobService.class), true);
        }
    }
    jobManager = new JobManager(builder.build());
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) MyJobService(com.birbit.android.jobqueue.examples.twitter.services.MyJobService) CustomLogger(com.birbit.android.jobqueue.log.CustomLogger) JobManager(com.birbit.android.jobqueue.JobManager) MyGcmJobService(com.birbit.android.jobqueue.examples.twitter.services.MyGcmJobService)

Example 28 with JobManager

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

the class InjectorTest method testInjector.

@Test
public void testInjector() throws Throwable {
    Configuration.Builder builder = new Configuration.Builder(RuntimeEnvironment.application);
    final JobManagerTestBase.ObjectReference injectedJobReference = new JobManagerTestBase.ObjectReference();
    final AtomicInteger injectionCallCount = new AtomicInteger(0);
    DependencyInjector dependencyInjector = new DependencyInjector() {

        @Override
        public void inject(Job job) {
            injectedJobReference.setObject(job);
            injectionCallCount.incrementAndGet();
        }
    };
    builder.injector(dependencyInjector);
    builder.timer(mockTimer);
    JobManager jobManager = createJobManager(builder);
    jobManager.stop();
    jobManager.addJob(new DummyJob(new Params(4)));
    MatcherAssert.assertThat("injection should be called after adding a non-persistent job", injectionCallCount.get(), equalTo(1));
    jobManager.addJob(new DummyJob(new Params(1).persist()));
    MatcherAssert.assertThat("injection should be called after adding a persistent job", injectionCallCount.get(), equalTo(2));
    JobHolder holder = nextJob(jobManager);
    MatcherAssert.assertThat("injection should NOT be called for non persistent job", holder.getJob(), not(injectedJobReference.getObject()));
    MatcherAssert.assertThat("injection should be called once for non persistent job", injectionCallCount.get(), equalTo(2));
    holder = nextJob(jobManager);
    MatcherAssert.assertThat("injection should be called for persistent job", holder.getJob(), equalTo(injectedJobReference.getObject()));
    MatcherAssert.assertThat("injection should be called two times for persistent job", injectionCallCount.get(), equalTo(3));
}
Also used : DependencyInjector(com.birbit.android.jobqueue.di.DependencyInjector) Configuration(com.birbit.android.jobqueue.config.Configuration) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) JobHolder(com.birbit.android.jobqueue.JobHolder) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) Test(org.junit.Test)

Example 29 with JobManager

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

the class KeepAliveTest method testKeepAlive.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void testKeepAlive(final DummyNetworkUtil networkUtil) throws Exception {
    int keepAlive = 3;
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).consumerKeepAlive(keepAlive).networkUtil(networkUtil).timer(mockTimer));
    //give it a little time to create first consumer
    final CountDownLatch jobDone = new CountDownLatch(1);
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            jobDone.countDown();
        }
    });
    jobManager.addJob(new DummyJob(new Params(0)));
    // Sync on job manager to ensure it handled add requests
    jobManager.count();
    MatcherAssert.assertThat("there should be 1 thread  actively waiting for jobs", jobManager.getActiveConsumerCount(), equalTo(1));
    MatcherAssert.assertThat(jobDone.await(1, TimeUnit.MINUTES), CoreMatchers.is(true));
    // Sync on job manager to ensure it handled add requests
    jobManager.count();
    mockTimer.incrementNs((long) (JobManager.NETWORK_CHECK_INTERVAL + TimeUnit.SECONDS.toNanos(keepAlive) + 1));
    FutureTask<Void> waitForConsumersFuture = new FutureTask<>(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            jobManager.waitUntilConsumersAreFinished();
            return null;
        }
    });
    new Thread(waitForConsumersFuture).start();
    waitForConsumersFuture.get(keepAlive * 10, TimeUnit.SECONDS);
    jobManager.waitUntilConsumersAreFinished();
    MatcherAssert.assertThat("after keep alive timeout, there should NOT be any threads waiting", jobManager.getActiveConsumerCount(), equalTo(0));
    //disable network and add a network bound job
    networkUtil.setNetworkStatus(NetworkUtil.DISCONNECTED);
    final DummyJob dj1 = new DummyJob(new Params(0).requireNetwork());
    jobManager.addJob(dj1);
    // sync add job request
    jobManager.count();
    mockTimer.incrementNs(JobManager.NETWORK_CHECK_INTERVAL + TimeUnit.SECONDS.toNanos(keepAlive) * 2);
    waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {

        @Override
        public void run() {
            networkUtil.setNetworkStatus(NetworkUtil.METERED);
        }

        @Override
        public void assertJob(Job job) {
            Assert.assertThat("it should be dj1", job, is((Job) dj1));
        }
    });
    MatcherAssert.assertThat("when network is recovered, job should be handled", jobManager.count(), equalTo(0));
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) FutureTask(java.util.concurrent.FutureTask) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) TargetApi(android.annotation.TargetApi)

Example 30 with JobManager

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

the class LoadFactorTest method testGoIdleIfNextJobCannotBeRunNow.

@SuppressLint("SLEEP_IN_CODE")
@Test
public void testGoIdleIfNextJobCannotBeRunNow() throws InterruptedException {
    // see: https://github.com/yigit/android-priority-jobqueue/issues/262
    final AtomicInteger nextJobDelayCall = new AtomicInteger(1);
    JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).maxConsumerCount(3).minConsumerCount(1).loadFactor(3).queueFactory(new QueueFactory() {

        @Override
        public JobQueue createPersistentQueue(Configuration configuration, long sessionId) {
            return new SqliteJobQueue(configuration, sessionId, new SqliteJobQueue.JavaSerializer());
        }

        @Override
        public JobQueue createNonPersistent(Configuration configuration, long sessionId) {
            return new SimpleInMemoryPriorityQueue(configuration, sessionId) {

                @Override
                public Long getNextJobDelayUntilNs(@NonNull Constraint constraint) {
                    nextJobDelayCall.incrementAndGet();
                    return super.getNextJobDelayUntilNs(constraint);
                }
            };
        }
    }).timer(mockTimer));
    final DummyJobWithStartEndLatch job1 = new DummyJobWithStartEndLatch(new Params(1));
    final DummyJobWithStartEndLatch job2 = new DummyJobWithStartEndLatch(new Params(1));
    jobManager.addJob(job1);
    jobManager.addJob(job2);
    assertThat(startLatch.await(5, TimeUnit.MINUTES), is(true));
    // give it some time to cool down, ugly but nothing to do
    Thread.sleep(2000);
    int startCount = nextJobDelayCall.get();
    Thread.sleep(5000);
    assertThat("JobManager should not query any more next jobs", nextJobDelayCall.get(), is(startCount));
    waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {

        @Override
        public void run() {
            canEndLatch.countDown();
        }

        @Override
        public void assertJob(Job job) {
        }
    });
}
Also used : Configuration(com.birbit.android.jobqueue.config.Configuration) JobQueue(com.birbit.android.jobqueue.JobQueue) SqliteJobQueue(com.birbit.android.jobqueue.persistentQueue.sqlite.SqliteJobQueue) Constraint(com.birbit.android.jobqueue.Constraint) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) QueueFactory(com.birbit.android.jobqueue.QueueFactory) SuppressLint(android.annotation.SuppressLint) Constraint(com.birbit.android.jobqueue.Constraint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SqliteJobQueue(com.birbit.android.jobqueue.persistentQueue.sqlite.SqliteJobQueue) SimpleInMemoryPriorityQueue(com.birbit.android.jobqueue.inMemoryQueue.SimpleInMemoryPriorityQueue) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) Test(org.junit.Test) SuppressLint(android.annotation.SuppressLint)

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