Java Examples for java.util.concurrent.ScheduledExecutorService

The following java examples will help you to understand the usage of java.util.concurrent.ScheduledExecutorService. These source code samples are taken from different open source projects.

Example 1
Project: semiot-platform-master  File: PlainWampClientConnectorProvider.java View source code
@Override
public ScheduledExecutorService createScheduler() {
    NioEventLoopGroup scheduler = new NioEventLoopGroup(10, new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "WampClientEventLoop");
            t.setDaemon(true);
            return t;
        }
    });
    return scheduler;
}
Example 2
Project: amanuensis-master  File: ExecutorTest.java View source code
@Test
public void testExecutor() throws Exception {
    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleWithFixedDelay(new Runnable() {

        int count = 0;

        @Override
        public void run() {
            // TODO Auto-generated method stub
            ++count;
            System.out.printf("Execution count %d\n", count);
            if (count > 2) {
                executor.shutdown();
            }
        }
    }, 0, 1000, TimeUnit.MILLISECONDS);
    executor.awaitTermination(5000, TimeUnit.MILLISECONDS);
    System.out.println("Completed");
}
Example 3
Project: failsafe-master  File: Issue9.java View source code
public void test() throws Throwable {
    // Given - Fail twice then succeed
    AtomicInteger retryCounter = new AtomicInteger();
    Service service = mock(Service.class);
    when(service.connect()).thenThrow(failures(2, new IllegalStateException())).thenReturn(true);
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    Listeners<Boolean> listeners = new Listeners<Boolean>() {

        public void onRetry(Boolean result, Throwable failure) {
            retryCounter.incrementAndGet();
        }
    };
    Waiter waiter = new Waiter();
    // When
    AtomicInteger successCounter = new AtomicInteger();
    FailsafeFuture<Boolean> future = Failsafe.with(new RetryPolicy().withMaxRetries(2)).with(executor).with(listeners).onSuccess( p -> {
        successCounter.incrementAndGet();
        waiter.resume();
    }).get(() -> service.connect());
    // Then
    waiter.await(1000);
    verify(service, times(3)).connect();
    assertEquals(future.get().booleanValue(), true);
    assertEquals(retryCounter.get(), 2);
    assertEquals(successCounter.get(), 1);
}
Example 4
Project: spring-js-master  File: ScheduledTaskRegistrar.java View source code
/**
	 * Set the {@link org.springframework.scheduling.TaskScheduler} to register scheduled
	 * tasks with, or a {@link java.util.concurrent.ScheduledExecutorService} to be
	 * wrapped as a TaskScheduler.
	 */
public void setScheduler(Object scheduler) {
    Assert.notNull(scheduler, "Scheduler object must not be null");
    if (scheduler instanceof TaskScheduler) {
        this.taskScheduler = (TaskScheduler) scheduler;
    } else if (scheduler instanceof ScheduledExecutorService) {
        this.taskScheduler = new ConcurrentTaskScheduler(((ScheduledExecutorService) scheduler));
    } else {
        throw new IllegalArgumentException("Unsupported scheduler type: " + scheduler.getClass());
    }
}
Example 5
Project: spring-framework-2.5.x-master  File: ScheduledExecutorFactoryBean.java View source code
public void afterPropertiesSet() {
    if (logger.isInfoEnabled()) {
        logger.info("Initializing ScheduledExecutorService" + (this.beanName != null ? " '" + this.beanName + "'" : ""));
    }
    ScheduledExecutorService executor = createExecutor(this.poolSize, this.threadFactory, this.rejectedExecutionHandler);
    // Register specified ScheduledExecutorTasks, if necessary.
    if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
        registerTasks(this.scheduledExecutorTasks, executor);
    }
    // Wrap executor with an unconfigurable decorator.
    this.executor = (this.exposeUnconfigurableExecutor ? Executors.unconfigurableScheduledExecutorService(executor) : executor);
}
Example 6
Project: Blazar-master  File: BlazarQueueProcessorModule.java View source code
@Override
public void configure(Binder binder) {
    Multibinder.newSetBinder(binder, LeaderLatchListener.class).addBinding().to(QueueProcessor.class);
    binder.bind(ScheduledExecutorService.class).annotatedWith(Names.named("QueueProcessor")).toProvider(new ManagedScheduledExecutorServiceProvider(1, "QueueProcessor")).in(Scopes.SINGLETON);
}
Example 7
Project: commafeed-master  File: ScheduledTask.java View source code
public void register(ScheduledExecutorService executor) {
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                ScheduledTask.this.run();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    };
    log.info("registering task {} for execution every {} {}, starting in {} {}", getClass().getSimpleName(), getPeriod(), getTimeUnit(), getInitialDelay(), getTimeUnit());
    executor.scheduleWithFixedDelay(runnable, getInitialDelay(), getPeriod(), getTimeUnit());
}
Example 8
Project: DisJob-master  File: SelfTestRMSMonitor.java View source code
public static final ScheduledExecutorService createExecutorService(int corePollSize) {
    return new ScheduledThreadPoolExecutor(corePollSize, new ThreadFactory() {

        private final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("thread-rms-monitor-selftest-" + ATOMIC_INTEGER.incrementAndGet());
            thread.setDaemon(true);
            return thread;
        }
    }, rmsDiscardPolicy);
}
Example 9
Project: javaee7-samples-master  File: ReceptionSynchronizerTest.java View source code
@Test
public void testWaiting() throws NoSuchMethodException, InterruptedException {
    final ReceptionSynchronizer cut = new ReceptionSynchronizer();
    ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    final Method method = ReceptionSynchronizerTest.class.getDeclaredMethod("testWaiting");
    long startTime = System.currentTimeMillis();
    pool.schedule(new Runnable() {

        @Override
        public void run() {
            cut.registerInvocation(method);
        }
    }, 1, TimeUnit.SECONDS);
    ReceptionSynchronizer.waitFor(ReceptionSynchronizerTest.class, "testWaiting");
    long waitTime = System.currentTimeMillis() - startTime;
    assertTrue("Waited more than 950ms", waitTime > 950);
    assertTrue("Waited no longer than 1050ms", waitTime < 1050);
}
Example 10
Project: JavaIncrementalParser-master  File: ReceptionSynchronizerTest.java View source code
@Test
public void testWaiting() throws NoSuchMethodException, InterruptedException {
    final ReceptionSynchronizer cut = new ReceptionSynchronizer();
    ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    final Method method = ReceptionSynchronizerTest.class.getDeclaredMethod("testWaiting");
    long startTime = System.currentTimeMillis();
    pool.schedule(new Runnable() {

        @Override
        public void run() {
            cut.registerInvocation(method);
        }
    }, 1, TimeUnit.SECONDS);
    ReceptionSynchronizer.waitFor(ReceptionSynchronizerTest.class, "testWaiting");
    long waitTime = System.currentTimeMillis() - startTime;
    assertTrue("Waited more than 950ms", waitTime > 950);
    assertTrue("Waited no longer than 1050ms", waitTime < 1050);
}
Example 11
Project: JavaStudy-master  File: TestScheduledThreadPool.java View source code
public static void main(String[] args) {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
    /**
		 * 延迟3秒执行
		 */
    /*scheduledThreadPool.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("delay 3 seconds");
			}
		}, 3, TimeUnit.SECONDS);*/
    /**
		 * 延迟1秒��3秒执行一次
		 */
    scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            System.out.println("delay 1 seconds, and excute every 3 seconds");
        }
    }, 1, 3, TimeUnit.SECONDS);
//		scheduledThreadPool.shutdown();
}
Example 12
Project: OG-Platform-master  File: InMemoryFunctionBlacklistProviderTest.java View source code
public void testGetBlacklist() {
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        final InMemoryFunctionBlacklistProvider provider = new InMemoryFunctionBlacklistProvider(executor);
        final FunctionBlacklist foo = provider.getBlacklist("Foo");
        assertEquals(foo.getName(), "Foo");
        final FunctionBlacklist bar = provider.getBlacklist("Bar");
        assertEquals(bar.getName(), "Bar");
        assertNotSame(foo, bar);
        final FunctionBlacklist foo2 = provider.getBlacklist("Foo");
        assertSame(foo2, foo);
    } finally {
        executor.shutdown();
    }
}
Example 13
Project: phoenix-app-ng-master  File: OnCompleteFutureTest.java View source code
@Test
public void testFutureGet() throws ExecutionException, InterruptedException {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    final OnCompleteFuture<Long> future = new OnCompleteFuture<>();
    service.schedule(new Runnable() {

        @Override
        public void run() {
            future.setValue(1000l);
        }
    }, 1000, TimeUnit.MILLISECONDS);
    assertEquals(Long.valueOf(1000), future.get());
}
Example 14
Project: spring-framework-master  File: ConcurrentTaskScheduler.java View source code
/**
	 * Specify the {@link java.util.concurrent.ScheduledExecutorService} to delegate to.
	 * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
	 * in order to use it for trigger-based scheduling if possible,
	 * instead of Spring's local trigger management.
	 * <p>Note: This will only apply to {@link TaskScheduler} invocations.
	 * If you want the given executor to apply to
	 * {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
	 * as well, pass the same executor reference to {@link #setConcurrentExecutor}.
	 * @see #setConcurrentExecutor
	 */
public final void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
    if (scheduledExecutor != null) {
        this.scheduledExecutor = scheduledExecutor;
        this.enterpriseConcurrentScheduler = (managedScheduledExecutorServiceClass != null && managedScheduledExecutorServiceClass.isInstance(scheduledExecutor));
    } else {
        this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        this.enterpriseConcurrentScheduler = false;
    }
}
Example 15
Project: audit4j-core-master  File: ConcurrentTaskScheduler.java View source code
/**
     * Specify the {@link java.util.concurrent.ScheduledExecutorService} to
     * delegate to.
     * <p>
     * Autodetects a JSR-236
     * 
     * @param scheduledExecutor
     *            the new scheduled executor
     *            {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
     *            in order to use it for trigger-based scheduling if possible,
     *            instead of Spring's local trigger management.
     *            <p>
     *            Note: This will only apply to {@link TaskScheduler}
     *            invocations. If you want the given executor to apply to
     *            {@link org.springframework.scheduling.SchedulingTaskExecutor}
     *            invocations as well, pass the same executor reference to
     *            {@link #setConcurrentExecutor}.
     * @see #setConcurrentExecutor
     */
public final void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
    if (scheduledExecutor != null) {
        this.scheduledExecutor = scheduledExecutor;
        this.enterpriseConcurrentScheduler = managedScheduledExecutorServiceClass != null && managedScheduledExecutorServiceClass.isInstance(scheduledExecutor);
    } else {
        this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        this.enterpriseConcurrentScheduler = false;
    }
}
Example 16
Project: airlift-master  File: TestDiscoveryModule.java View source code
@Test
public void testExecutorShutdown() throws Exception {
    Bootstrap app = new Bootstrap(new JsonModule(), new TestingNodeModule(), new DiscoveryModule());
    Injector injector = app.strictConfig().doNotInitializeLogging().initialize();
    ExecutorService executor = injector.getInstance(Key.get(ScheduledExecutorService.class, ForDiscoveryClient.class));
    LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class);
    assertFalse(executor.isShutdown());
    lifeCycleManager.stop();
    assertTrue(executor.isShutdown());
}
Example 17
Project: AutoGrader-master  File: TimeLimit.java View source code
public void startTime(int time, String RegNo, int type) {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    Runnable runnable = () -> {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                lastJob(RegNo, type);
            }
        });
    };
    // Run it in x mins - you would have to calculate how long to wait from "now"
    // Call functions after this
    service.schedule(runnable, time, TimeUnit.SECONDS);
}
Example 18
Project: avro-mr-master  File: MuxDemuxRunnableTest.java View source code
@Test
public void test() {
    File dir = new File(MuxDemuxRunnable.COLLECTOR_LOCATION);
    int expected = -1;
    String files[] = dir.list();
    for (String f : files) {
        try {
            MuxDemuxValidate.validateCollectorsFile(dir.getAbsolutePath().concat("/").concat(f));
            expected = 0;
        } catch (IOException e) {
            Assert.assertEquals("Failed to validate collector files: " + e.getMessage(), 0, expected);
            e.printStackTrace();
        }
    }
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.execute(new MuxDemuxRunnable(APPID));
    expected = -1;
    try {
        Thread.sleep((int) (// 1min
        1 * 60 * // 1min
        1000));
        expected = 0;
    } catch (Exception e) {
        Assert.assertEquals("Failed to validate collector files: " + e.getMessage(), 0, expected);
        e.printStackTrace();
    } finally {
        service.shutdown();
    }
    expected = -1;
    try {
        MuxDemuxValidate.validateMuxDemuxFile(APPID, cal.getTimeInMillis());
        expected = 0;
    } catch (Exception e) {
        Assert.assertEquals("Failed to validate mux demux file: " + e.getMessage(), 0, expected);
    }
}
Example 19
Project: cucumber-jvm-master  File: Timeout.java View source code
public static <T> T timeout(Callback<T> callback, long timeoutMillis) throws Throwable {
    if (timeoutMillis == 0) {
        return callback.call();
    } else {
        final Thread executionThread = Thread.currentThread();
        final AtomicBoolean done = new AtomicBoolean();
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> timer = executorService.schedule(new Runnable() {

            @Override
            public void run() {
                if (!done.get()) {
                    executionThread.interrupt();
                }
            }
        }, timeoutMillis, TimeUnit.MILLISECONDS);
        try {
            return callback.call();
        } catch (InterruptedException timeout) {
            throw new TimeoutException("Timed out after " + timeoutMillis + "ms.");
        } finally {
            done.set(true);
            timer.cancel(true);
            executorService.shutdownNow();
        }
    }
}
Example 20
Project: dse_driver_examples-master  File: JAVA_577.java View source code
public static void main(String args[]) {
    Cluster cluster = Cluster.builder().addContactPoint("130.211.158.230").build();
    cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(5);
    cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(20);
    final Session session = cluster.connect("java577");
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(100);
    for (int i = 0; i < 100; ++i) {
        executorService.execute(new Runnable() {

            int count = 0;

            @Override
            public void run() {
                while (true) {
                    try {
                        ResultSet rs = session.execute("select * from testks.record4 limit 1000;");
                        Host queriedHost = rs.getExecutionInfo().getQueriedHost();
                        System.out.println("Invoking " + Thread.currentThread().getName() + " : " + count++ + " against the host " + queriedHost);
                    } catch (Exception e) {
                        String message = e.getMessage();
                        if (!message.contains("timeout during read query")) {
                            System.out.println("Exception " + e.getMessage());
                        }
                    }
                    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
                }
            }
        });
    }
    Uninterruptibles.sleepUninterruptibly(100, TimeUnit.HOURS);
}
Example 21
Project: java-core-learning-example-master  File: SchedulerExecutorTest.java View source code
public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    // 一秒
    executor.scheduleAtFixedRate(new SchedulerExecutorTest("job1"), 1, 1, TimeUnit.SECONDS);
    // 两秒
    executor.scheduleWithFixedDelay(new SchedulerExecutorTest("job2"), 1, 2, TimeUnit.SECONDS);
}
Example 22
Project: jxse-master  File: SrdiManagerPeriodicPushTaskTest.java View source code
@Before
public void setUp() throws Exception {
    mockery = new JUnit4Mockery();
    srdiInterfaceMock = mockery.mock(SrdiPushEntriesInterface.class);
    executorServiceMock = mockery.mock(ScheduledExecutorService.class);
    runHandleMock = mockery.mock(ScheduledFuture.class);
    pushTask = new SrdiManagerPeriodicPushTask("testHandler", srdiInterfaceMock, executorServiceMock, PUSH_INTERVAL);
}
Example 23
Project: jxta-master  File: SelfCancellingTaskTest.java View source code
public void testCancel() throws Exception {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    SelfCancellingTaskTester tester = new SelfCancellingTaskTester(5);
    ScheduledFuture<?> handle = executor.scheduleAtFixedRate(tester, 100L, 100L, TimeUnit.MILLISECONDS);
    tester.setHandle(handle);
    Thread.sleep(1000L);
    executor.shutdown();
    boolean terminated = executor.awaitTermination(100L, TimeUnit.MILLISECONDS);
    assertTrue(terminated);
    assertTrue(handle.isCancelled());
    assertEquals(5, tester.getRunCount());
}
Example 24
Project: netflix-commons-master  File: ConcurrencyModuleTest.java View source code
@Test
public void shouldUseOverrideModule() {
    Injector injector = LifecycleInjector.builder().withRootModule(ConcurrencyModule.class).withBootstrapModule(new BootstrapModule() {

        @Override
        public void configure(BootstrapBinder binder) {
            binder.bind(ConcurrencyModule.class).toInstance(new ConcurrencyModule() {

                @Override
                protected void configure() {
                }
            });
        }
    }).build().createInjector();
    try {
        ScheduledExecutorService service = injector.getInstance(Key.get(ScheduledExecutorService.class, Background.class));
        Assert.fail("Binding shouldn't exist");
    } catch (ConfigurationException e) {
    }
}
Example 25
Project: netty-in-action-master  File: ScheduleExamples.java View source code
/**
     * Listing 14.4
     */
public static void schedule() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    ScheduledFuture<?> future = executor.schedule(new Runnable() {

        @Override
        public void run() {
            System.out.println("Now it is 60 seconds later");
        }
    }, 60, TimeUnit.SECONDS);
    // do something
    //
    executor.shutdown();
}
Example 26
Project: NettyGameServer-master  File: ScheduledThreadPoolExecutorTest.java View source code
public static void main(String[] args) {
    /**
         * 使用工厂方法�始化一个ScheduledThreadPool
         */
    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(2);
    TimerTask task1 = new TimerTask() {

        @Override
        public void run() {
            try {
                System.out.println("task1 invoked ! " + (System.currentTimeMillis() - start));
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    TimerTask task2 = new TimerTask() {

        @Override
        public void run() {
            System.out.println("task2 invoked ! " + (System.currentTimeMillis() - start));
        }
    };
    start = System.currentTimeMillis();
    newScheduledThreadPool.schedule(task1, 1000, TimeUnit.MILLISECONDS);
    //        newScheduledThreadPool.scheduleAtFixedRate(task1, 1000, 1000, TimeUnit.MICROSECONDS);
    newScheduledThreadPool.schedule(task2, 3000, TimeUnit.MILLISECONDS);
}
Example 27
Project: ovirt-engine-master  File: ShutdownHook.java View source code
@Override
public void run() {
    log.info("Preparing for shutdown after receiving signal ");
    for (ScheduledFuture<?> scheduled : serviceHandlers) {
        scheduled.cancel(true);
    }
    for (ScheduledExecutorService executer : schedulers) {
        executer.shutdown();
    }
    log.info("Event Notification service was shutdown");
}
Example 28
Project: RocketMQ-master  File: SystemClock.java View source code
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, precision, precision, TimeUnit.MILLISECONDS);
}
Example 29
Project: Singularity-master  File: SingularityManagedScheduledExecutorServiceFactory.java View source code
@Override
public void stop() throws Exception {
    if (!stopped.getAndSet(true)) {
        for (ScheduledExecutorService service : executorPools) {
            service.shutdown();
        }
        long timeoutLeftInMillis = timeoutInMillis;
        for (ScheduledExecutorService service : executorPools) {
            final long start = System.currentTimeMillis();
            if (!service.awaitTermination(timeoutLeftInMillis, TimeUnit.MILLISECONDS)) {
                return;
            }
            timeoutLeftInMillis -= (System.currentTimeMillis() - start);
        }
    }
}
Example 30
Project: timey-master  File: SimpleAlarm.java View source code
/**
	 * Startet die Alarmerkennung.
	 *
	 * @param delayPerThread
	 *            Maßzahl für den Ausfuehrungsintervall
	 * @param timeUnit
	 *            Einheit für den Ausfuehrungsintervall
	 */
public void startAlarmdetection(final int delayPerThread, final TimeUnit timeUnit) {
    if (delayPerThread < 1) {
        throw new ValueMinimumArgumentException();
    } else if (timeUnit == null) {
        throw new NullArgumentException();
    }
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
    final AlarmRunnable alarmDetection = (AlarmRunnable) this.springContext.getBean("alarmRunnable");
    scheduler.scheduleAtFixedRate(alarmDetection, 0, delayPerThread, timeUnit);
}
Example 31
Project: webpie-master  File: HttpFrontendFactory.java View source code
/**
	 * 
	 * @param id Use for logging and also file recording names
	 * @param threadPoolSize The size of the threadpool, although all data comes in order as we
	 * use the SessionExecutorImpl found in webpieces
	 * 
	 * @return
	 */
public static HttpFrontendManager createFrontEnd(String id, int threadPoolSize, ScheduledExecutorService timer, BufferPool pool) {
    Executor executor = Executors.newFixedThreadPool(threadPoolSize, new NamedThreadFactory(id));
    ChannelManagerFactory factory = ChannelManagerFactory.createFactory();
    ChannelManager chanMgr = factory.createMultiThreadedChanMgr(id, pool, executor);
    AsyncServerManager svrMgr = AsyncServerMgrFactory.createAsyncServer(chanMgr);
    return createFrontEnd(svrMgr, timer, pool);
}
Example 32
Project: servoy-client-master  File: ServoyScheduledExecutor.java View source code
/**
	 * @param scheduledExecutorSize
	 */
private synchronized ScheduledExecutorService getScheduledExecutorService() {
    if (scheduledService == null) {
        scheduledService = new ScheduledThreadPoolExecutor(scheduledExecutorSize, getThreadFactory(), getRejectedExecutionHandler()) {

            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                ServoyScheduledExecutor.this.beforeExecute(t, r);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                ServoyScheduledExecutor.this.afterExecute(r, t);
            }
        };
    }
    return scheduledService;
}
Example 33
Project: aceim-master  File: ICQProtocol.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    if (!isRunning) {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.schedule(new Runnable() {

            @Override
            public void run() {
                for (final ICQService service : mAccountServices) {
                    if (service.getCurrentState() != ConnectionState.DISCONNECTED) {
                        service.getProtocol().disconnect();
                    }
                }
                isRunning = false;
            }
        }, 2, TimeUnit.SECONDS);
    }
}
Example 34
Project: BingAds-Java-SDK-master  File: OperationStatusRetry.java View source code
private void retry(final TriConsumer<TOperationStatusProvider, ServiceClient<TService>, AsyncCallback<TOperationStatus>> action, final TOperationStatusProvider statusProvider, final ServiceClient<TService> serviceClient, final Consumer<TOperationStatus> statusConsumer, final Consumer<Exception> exceptionConsumer, final int maxRetryCount) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.schedule(new Runnable() {

        @Override
        public void run() {
            executeWithRetry(action, statusProvider, serviceClient, statusConsumer, exceptionConsumer, maxRetryCount - 1);
        }
    }, INTERVAL_OF_RETRY, TimeUnit.MILLISECONDS);
}
Example 35
Project: blucat-master  File: PairUtil.java View source code
public static boolean testpair(String mac) {
    PrintUtil.out.println("#Trying to trigger a pair");
    //for (int i = 1; i <= 30; i++){
    String url = "btl2cap://" + mac + ":" + 3;
    String fullurl = url + ";authenticate=false;encrypt=false";
    //PrintUtil.out.println(url);
    // fun 
    // /System/Library/CoreServices/BluetoothUIServer.app/Contents/MacOS/BluetoothUIServer -numeric 00-00-00-00-ca-fe 0000
    BlucatState.rssiexec = Executors.newSingleThreadScheduledExecutor();
    BlucatState.rssiexec.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                PrintUtil.vverbose("#killing pairing windows");
                // Get the ui out of the way
                Runtime.getRuntime().exec("killall BluetoothUIServer");
            } catch (Exception e) {
                PrintUtil.verbose("#Unable to end");
            }
        }
    }, 1, 1, TimeUnit.SECONDS);
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    es.schedule(new Runnable() {

        @Override
        public void run() {
            try {
                PrintUtil.out.println("#Timeout!");
                System.exit(1);
            } catch (Exception e) {
                PrintUtil.verbose("#Unable to end");
            }
        }
    }, BlucatState.timeout / 1000, TimeUnit.SECONDS);
    try {
        Connection con = Connector.open(fullurl, Connector.READ_WRITE, true);
        PrintUtil.out.println("#Connected");
        con.close();
        return true;
    } catch (IllegalArgumentException a) {
        PrintUtil.out.println("#Tell Joe to fix this for your platform");
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg.contains("0x00000004")) {
            PrintUtil.out.println("#They seem to be out of range");
        } else if (msg.contains("0x00000005")) {
            PrintUtil.out.println("#A pairing request should have happened");
        } else {
            PrintUtil.out.println(msg);
        }
    }
    return false;
}
Example 36
Project: blynk-server-master  File: JobLauncher.java View source code
public static void start(Holder holder, BaseServer[] servers) {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    long startDelay;
    ReportingWorker reportingWorker = new ReportingWorker(holder.reportingDao, ReportingUtil.getReportingFolder(holder.props.getProperty("data.folder")), holder.dbManager);
    //to start at the beggining of an minute
    startDelay = AverageAggregatorProcessor.MINUTE - (System.currentTimeMillis() % AverageAggregatorProcessor.MINUTE);
    scheduler.scheduleAtFixedRate(reportingWorker, startDelay, AverageAggregatorProcessor.MINUTE, TimeUnit.MILLISECONDS);
    ProfileSaverWorker profileSaverWorker = new ProfileSaverWorker(holder.userDao, holder.fileManager, holder.dbManager);
    //running 1 sec later after reporting
    scheduler.scheduleAtFixedRate(profileSaverWorker, startDelay + 1000, holder.props.getIntProperty("profile.save.worker.period"), TimeUnit.MILLISECONDS);
    StatsWorker statsWorker = new StatsWorker(holder);
    scheduler.scheduleAtFixedRate(statsWorker, 1000, holder.props.getIntProperty("stats.print.worker.period"), TimeUnit.MILLISECONDS);
    if (holder.sslContextHolder.isAutoGenerationEnabled) {
        scheduler.scheduleAtFixedRate(new CertificateRenewalWorker(holder.sslContextHolder.acmeClient, 7), 1, 1, TimeUnit.DAYS);
    }
    //millis we need to wait to start scheduler at the beginning of a second.
    startDelay = 1000 - (System.currentTimeMillis() % 1000);
    //separate thread for timer and reading widgets
    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
    ses.scheduleAtFixedRate(holder.timerWorker, startDelay, 1000, TimeUnit.MILLISECONDS);
    ses.scheduleAtFixedRate(holder.readingWidgetsWorker, startDelay + 400, 1000, TimeUnit.MILLISECONDS);
    //shutdown hook thread catcher
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHookWorker(servers, holder, scheduler, profileSaverWorker)));
}
Example 37
Project: camel-master  File: TimerListenerManagerTest.java View source code
public void testTimerListenerManager() throws Exception {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    TimerListenerManager manager = new TimerListenerManager();
    manager.setCamelContext(context);
    manager.addTimerListener(task);
    manager.start();
    assertTrue("Should be invoked", task.await());
    manager.stop();
    manager.removeTimerListener(task);
    executor.shutdown();
}
Example 38
Project: camelinaction2-master  File: AggregateTimeoutThreadpoolTest.java View source code
@Override
public void configure() throws Exception {
    ScheduledExecutorService threadPool = context.getExecutorServiceManager().newScheduledThreadPool(this, "MyThreadPool", 2);
    from("direct:start").log("Sending ${body}").aggregate(// use class MyAggregationStrategy for aggregation
    xpath("/order/@customer"), new MyAggregationStrategy()).completionSize(// complete either when we have 2 messages or after 5 sec timeout
    2).completionTimeout(5000).timeoutCheckerExecutorService(threadPool).log(// do a little logging for the published message
    "Completed by ${exchangeProperty.CamelAggregatedCompletedBy}").log("Sending out ${body}").to(// and send it to the mock
    "mock:result");
}
Example 39
Project: deft-master  File: JMXDebuggableCallbackManagerTest.java View source code
@Test
public void concurrencyTest() {
    final int nThreads = 25;
    final int n = 20 * 1000;
    final int[] exceptionThrown = { 0 };
    Runnable ioLoopTask = new Runnable() {

        public void run() {
            try {
                cm.execute();
            } catch (Exception e) {
                exceptionThrown[0] = 1;
            }
        }
    };
    ScheduledExecutorService ioLoop = Executors.newSingleThreadScheduledExecutor();
    ioLoop.scheduleAtFixedRate(ioLoopTask, 0, 1, TimeUnit.MILLISECONDS);
    final CountDownLatch latch = new CountDownLatch(n);
    ScheduledExecutorService workerThreads = Executors.newScheduledThreadPool(nThreads);
    Runnable work = new Runnable() {

        public void run() {
            cm.addCallback(AsyncCallback.nopCb);
            latch.countDown();
        }
    };
    for (int i = 0; i < 25; i++) {
        workerThreads.scheduleWithFixedDelay(work, 0, 1, TimeUnit.MILLISECONDS);
    }
    try {
        latch.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        assertTrue(false);
    }
    assertEquals(0, latch.getCount());
    assertEquals(0, exceptionThrown[0]);
    ioLoop.shutdownNow();
    workerThreads.shutdownNow();
}
Example 40
Project: dyn53-master  File: ExternalIpModule.java View source code
@Override
protected void configure() {
    Multibinder.newSetBinder(binder(), Lifecycle.class).addBinding().to(ExternalIpDiscoveryLifecycle.class);
    bind(Runnable.class).to(ExternalIpDiscoveryCommand.class);
    bind(ScheduledExecutorService.class).toInstance(Executors.newSingleThreadScheduledExecutor(new NamedPoolThreadFactory("externalIpDiscovery")));
    bind(Long.class).annotatedWith(Names.named("initialDelay")).toInstance(0L);
    bind(Long.class).annotatedWith(Names.named("delay")).toInstance(300L);
}
Example 41
Project: Dzh-perfutil-master  File: LogHistogramLoggerMoreTest.java View source code
@Test
public void testBogusInterval() throws Exception {
    assertFalse(gotMessage);
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    LogHistogramLogger lhl = new LogHistogramLogger(ses, 17, new LogHistogramLogger.Listener() {

        @Override
        public void intervalRecorded(RecordedInterval<LogHistogramRecorder> i) {
            gotMessage = true;
        }
    });
    assertNotNull(lhl);
    assertFalse(gotMessage);
    Thread.sleep(20);
    assertTrue(gotMessage);
}
Example 42
Project: ecs-sync-master  File: PerformanceWindowMultiTest.java View source code
public static void main(String[] args) throws Exception {
    pw = new PerformanceWindow(500, 10);
    // Pattern
    String layoutString = "%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c{1}:%L - %m%n";
    PatternLayout layout = new PatternLayout(layoutString);
    // Appender
    Appender appender = new ConsoleAppender(layout, "System.err");
    LogManager.getRootLogger().addAppender(appender);
    LogManager.getRootLogger().setLevel(Level.TRACE);
    ScheduledExecutorService se = Executors.newScheduledThreadPool(5);
    System.out.println("Adding one @ 1000b/s");
    se.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            pw.increment(1000);
        }
    }, 1, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    System.out.println("Adding another @ 32kB/s");
    se.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            pw.increment(32 * 1024);
        }
    }, 1, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    System.out.println("Adding a fast one @ 1MB/s");
    se.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            pw.increment(1024);
        }
    }, 1, 1, TimeUnit.MILLISECONDS);
    Thread.sleep(10000);
    System.out.println("Adding another fast one @ 100MB/s");
    se.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            pw.increment(128 * 1024);
        }
    }, 1, 1, TimeUnit.MILLISECONDS);
    Thread.sleep(100000);
    System.exit(0);
}
Example 43
Project: eventtracker-master  File: MockCollectorControllerModule.java View source code
@Override
protected void configure() {
    final EventTrackerConfig config = new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class);
    bind(EventTrackerConfig.class).toInstance(config);
    final EventSender eventSender = new MockCollectorSender();
    bind(EventSender.class).toInstance(eventSender);
    final ScheduledExecutorService executor = new StubScheduledExecutorService() {

        public AtomicBoolean isShutdown = new AtomicBoolean(false);

        @Override
        public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
            return true;
        }

        @Override
        public void shutdown() {
            isShutdown.set(true);
        }

        @Override
        public List<Runnable> shutdownNow() {
            isShutdown.set(true);
            return new ArrayList<Runnable>();
        }

        @Override
        public boolean isShutdown() {
            return isShutdown.get();
        }

        @Override
        public boolean isTerminated() {
            return isShutdown.get();
        }
    };
    bind(ScheduledExecutorService.class).toInstance(executor);
    bind(CollectorController.class).toProvider(CollectorControllerProvider.class).asEagerSingleton();
    bind(DiskSpoolEventWriter.class).toInstance(new DiskSpoolEventWriter(new EventHandler() {

        @Override
        public void handle(final File file, final CallbackHandler handler) {
            // Send a dummy event
            eventSender.send(file, handler);
        }
    }, config.getSpoolDirectoryName(), config.isFlushEnabled(), config.getFlushIntervalInSeconds(), executor, SyncType.valueOf(config.getSyncType()), config.getSyncBatchSize()));
    bind(EventWriter.class).toProvider(ThresholdEventWriterProvider.class);
}
Example 44
Project: gda-dal-master  File: ThermometerExample.java View source code
public static void main(String[] args) {
    final Shell shell = new Shell();
    shell.setSize(300, 250);
    shell.open();
    //use LightweightSystem to create the bridge between SWT and draw2D
    final LightweightSystem lws = new LightweightSystem(shell);
    //Create widget
    final ThermometerFigure thermo = new ThermometerFigure();
    //Init widget
    thermo.setBackgroundColor(XYGraphMediaFactory.getInstance().getColor(255, 255, 255));
    thermo.setBorder(new SchemeBorder(SchemeBorder.SCHEMES.ETCHED));
    thermo.setRange(-100, 100);
    thermo.setLoLevel(-50);
    thermo.setLoloLevel(-80);
    thermo.setHiLevel(60);
    thermo.setHihiLevel(80);
    thermo.setMajorTickMarkStepHint(50);
    lws.setContents(thermo);
    //Update the widget in another thread.
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    thermo.setValue(Math.sin(counter++ / 10.0) * 100);
                }
            });
        }
    }, 100, 100, TimeUnit.MILLISECONDS);
    Display display = Display.getDefault();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    future.cancel(true);
    scheduler.shutdown();
}
Example 45
Project: groupbasedpolicy-master  File: ReadGbpFlowCacheTaskTest.java View source code
@Before
public void init() {
    StatisticsManager statisticsManager = mock(StatisticsManager.class);
    ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
    ClientResponse clientResponse = mock(ClientResponse.class);
    response = mock(JsonRestClientResponse.class);
    when(response.getJsonResponse()).thenReturn("[{\"one\":1, \"two\":2, \"three\":3}]");
    when(response.getStatusCode()).thenReturn(200);
    when(response.getClientResponse()).thenReturn(clientResponse);
    SFlowRTConnection connection = mock(SFlowRTConnection.class);
    when(connection.get(anyString(), Mockito.<MultivaluedMap<String, String>>any())).thenReturn(response);
    when(connection.getExecutor()).thenReturn(executor);
    doNothing().when(executor).execute(any(Runnable.class));
    task = new ReadGbpFlowCacheTask("cache1", connection, statisticsManager, 100, 0.1, "sum");
}
Example 46
Project: hprose-java-master  File: Timer.java View source code
public void run() {
    ScheduledExecutorService timer = timer1;
    timer1 = Executors.newSingleThreadScheduledExecutor();
    timer.shutdownNow();
    timer = timer2;
    timer2 = Executors.newSingleThreadScheduledExecutor();
    List<Runnable> tasks = timer.shutdownNow();
    for (Runnable task : tasks) {
        task.run();
    }
}
Example 47
Project: imcache-master  File: ConcurrentLinkedHashMapTest.java View source code
@Test
public void concurrentLinkedHashMap() {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    int concurrencyLevel = 2;
    int initialCapacity = 2;
    int capacity = 2;
    long period = 3L;
    EvictionListener<Integer, Integer> evictionListener = new EvictionListener<Integer, Integer>() {

        @Override
        public void onEviction(Integer key, Integer value) {
        }
    };
    Weigher<Integer> weigher = Weighers.singleton();
    ConcurrentLinkedHashMap<Integer, Integer> map = new ConcurrentLinkedHashMap<Integer, Integer>(concurrencyLevel, capacity, initialCapacity, weigher, period, service, evictionListener);
    map.put(1, 2);
    map.ascendingKeySet();
    map.ascendingKeySetWithLimit(10);
    map.ascendingMap();
    map.ascendingMapWithLimit(10);
    assertEquals(capacity, map.capacity());
    assertFalse(map.containsKey(3));
    map.descendingKeySet();
    map.descendingKeySetWithLimit(10);
    map.descendingMap();
    map.descendingMapWithLimit(10);
    map.entrySet();
    assertTrue(map.keySet().contains(1));
    map.putAll(map);
    map.putIfAbsent(3, 4);
    map.remove(3);
    map.replace(1, 10);
    map.replace(1, 10, 100);
    map.setCapacity(20);
    map.size();
    map.isEmpty();
    map.weightedSize();
}
Example 48
Project: infinispan-master  File: ExpirationManagerTest.java View source code
public void testNoExpirationThread() {
    ExpirationManagerImpl em = new ExpirationManagerImpl();
    Configuration cfg = getCfg().expiration().wakeUpInterval(0L).build();
    ScheduledExecutorService mockService = mock(ScheduledExecutorService.class);
    em.initialize(mockService, "", cfg, null, null, null, null);
    em.start();
    assertNull("Expiration task is not null!  Should not have scheduled anything!", em.expirationTask);
}
Example 49
Project: java-driver-master  File: SingleConnectionPoolTest.java View source code
@Test(groups = "short")
public void should_throttle_requests() {
    // Throttle to a very low value. Even a single thread can generate a higher throughput.
    final int maxRequests = 10;
    cluster().getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
    // Track in flight requests in a dedicated thread every second
    final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
    final Host host = cluster().getMetadata().getHost(ccm().addressOfNode(1));
    ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
    final Runnable openConnectionsWatcher = new Runnable() {

        @Override
        public void run() {
            int inFlight = session().getState().getInFlightQueries(host);
            if (inFlight > maxRequests)
                excessInflightQueriesSpotted.set(true);
        }
    };
    openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 200, 200, TimeUnit.MILLISECONDS);
    // Generate the load
    for (int i = 0; i < 10000; i++) session().executeAsync("SELECT release_version FROM system.local");
    openConnectionsWatcherExecutor.shutdownNow();
    if (excessInflightQueriesSpotted.get()) {
        fail("Inflight queries exceeded the limit");
    }
}
Example 50
Project: java-game-server-master  File: ZombieJetclient.java View source code
public static void main(String[] args) throws Exception {
    LoginBuilder builder = new LoginBuilder().username("user").password("pass").connectionKey("Zombie_ROOM_1_REF_KEY_1").jetserverTcpHostName("localhost").tcpPort(18090).jetserverUdpHostName("255.255.255.255").udpPort(18090);
    LoginHelper loginHelper = builder.build();
    SessionFactory sessionFactory = new SessionFactory(loginHelper);
    ScheduledExecutorService taskExecutor = Executors.newSingleThreadScheduledExecutor();
    for (int i = 1; i <= 50; i++) {
        Session session = sessionFactory.createAndConnectSession();
        addDefaultHandlerToSession(session);
        GamePlay task = null;
        if ((i % 2) == 0) {
            task = new GamePlay(IAM.DEFENDER, session);
        } else {
            task = new GamePlay(IAM.ZOMBIE, session);
        }
        taskExecutor.scheduleAtFixedRate(task, 2000, 200, TimeUnit.MILLISECONDS);
    }
}
Example 51
Project: javacuriosities-master  File: Main.java View source code
public static void main(String[] args) {
    try {
        // Creamos un pool de 1 thread que será ejecutado cada cierto tiempo
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        // Creamos una tarea que será ejecutada cada 10 segundos
        final Runnable beeper = new Beeper();
        // Registramos en el scheduler esta tarea para ejecutarla cada 10 segundos sin delay
        final ScheduledFuture<?> beeperHandler = scheduler.scheduleAtFixedRate(beeper, 0, 10, TimeUnit.SECONDS);
        // Registramos otra tarea para ser ejecutada en 60 segundos
        scheduler.schedule(new BeeperCancel(beeperHandler), 60, TimeUnit.SECONDS);
        scheduler.awaitTermination(90, TimeUnit.SECONDS);
        scheduler.shutdown();
        while (!scheduler.isTerminated()) {
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Example 52
Project: jenkins-master  File: Timer.java View source code
/**
     * Returns the scheduled executor service used by all timed tasks in Jenkins.
     *
     * @return the single {@link ScheduledExecutorService}.
     */
@Nonnull
public static synchronized ScheduledExecutorService get() {
    if (executorService == null) {
        // corePoolSize is set to 10, but will only be created if needed.
        // ScheduledThreadPoolExecutor "acts as a fixed-sized pool using corePoolSize threads"
        executorService = new ErrorLoggingScheduledThreadPoolExecutor(10, new NamingThreadFactory(new DaemonThreadFactory(), "jenkins.util.Timer"));
    }
    return executorService;
}
Example 53
Project: Jest-master  File: IdleConnectionReaper.java View source code
@Override
protected ScheduledExecutorService executor() {
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat(serviceName()).build());
    // Add a listener to shutdown the executor after the service is stopped.  This ensures that the
    // JVM shutdown will not be prevented from exiting after this service has stopped or failed.
    // Technically this listener is added after start() was called so it is a little gross, but it
    // is called within doStart() so we know that the service cannot terminate or fail concurrently
    // with adding this listener so it is impossible to miss an event that we are interested in.
    addListener(new Listener() {

        @Override
        public void terminated(State from) {
            executor.shutdown();
        }

        @Override
        public void failed(State from, Throwable failure) {
            executor.shutdown();
        }
    }, MoreExecutors.directExecutor());
    return executor;
}
Example 54
Project: light-task-scheduler-master  File: SystemClock.java View source code
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("System Clock", true));
    scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, period, period, TimeUnit.MILLISECONDS);
}
Example 55
Project: limewire5-ruby-master  File: UptimeStatTimerTest.java View source code
public void testUpdateUptimeHistory() {
    ScheduledExecutorService service = new ScheduledExecutorServiceStub();
    UptimeStatTimer refreshTimer = new UptimeStatTimer(service);
    StringArraySetting uptimeHistory = ApplicationSettings.LAST_N_UPTIMES;
    assertEquals(new String[0], uptimeHistory.getValue());
    // ensure history is not updated
    for (int i = 0; i < 5; i++) {
        refreshTimer.updateUptimeHistory(i, 10, 10);
        assertEquals(new String[0], uptimeHistory.getValue());
    }
    // test for initialization
    refreshTimer.updateUptimeHistory(10, 10, 2);
    assertEquals(new String[] { "10" }, uptimeHistory.getValue());
    // regular update, should replace old value
    refreshTimer.updateUptimeHistory(20, 10, 2);
    assertEquals(new String[] { "20" }, uptimeHistory.getValue());
    // new first time update, should append
    refreshTimer = new UptimeStatTimer(service);
    refreshTimer.updateUptimeHistory(10, 10, 2);
    assertEquals(new String[] { "20", "10" }, uptimeHistory.getValue());
    // new first time update should shift array
    refreshTimer = new UptimeStatTimer(service);
    refreshTimer.updateUptimeHistory(10, 10, 2);
    assertEquals(new String[] { "10", "10" }, uptimeHistory.getValue());
    // regular update, should replace
    refreshTimer.updateUptimeHistory(30, 10, 2);
    assertEquals(new String[] { "10", "30" }, uptimeHistory.getValue());
    // go back to shorter history length
    refreshTimer = new UptimeStatTimer(service);
    refreshTimer.updateUptimeHistory(10, 10, 1);
    assertEquals(new String[] { "10" }, uptimeHistory.getValue());
    refreshTimer.updateUptimeHistory(20, 10, 1);
    assertEquals(new String[] { "20" }, uptimeHistory.getValue());
    // now with longer history, but not first interval
    refreshTimer.updateUptimeHistory(30, 10, 2);
    assertEquals(new String[] { "30" }, uptimeHistory.getValue());
}
Example 56
Project: live-chat-engine-master  File: ScheduledService_withFixedDelay.java View source code
public static void main(String[] args) throws IOException {
    ScheduledExecutorService pool = ExecutorsUtil.newScheduledThreadPool("test", 2);
    pool.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            System.out.println("1000");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 100, 1000, TimeUnit.MILLISECONDS);
    pool.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            System.out.println("500");
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 100, 500, TimeUnit.MILLISECONDS);
    pool.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            System.out.println("100");
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 100, 100, TimeUnit.MILLISECONDS);
    System.in.read();
}
Example 57
Project: magarena-master  File: CardImageWorker.java View source code
@Override
protected Image doInBackground() throws Exception {
    // if image not returned within specified millisecs,
    // set CardImagePanel to pending state.
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.schedule(() -> {
        publish(!isCancelled() && !isDone());
    }, 200, TimeUnit.MILLISECONDS);
    //        Thread.currentThread().sleep(ThreadLocalRandom.current().nextInt(100, 1000));
    Image image = CardViewer.getCardImage(card, viewerSize);
    executor.shutdownNow();
    return image;
}
Example 58
Project: mtools-master  File: SchedulTest.java View source code
public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    //		ScheduledExecutorService sch = Executors.newSingleThreadScheduledExecutor();
    //		
    //		sch.scheduleAtFixedRate(new Runnable(){
    //
    //			@Override
    //			public void run() {
    //				index++;
    //				System.out.println(index);
    //				
    //			}
    //			
    //		}, 1, 500, TimeUnit.MILLISECONDS);
    sch = new SchedulTest();
    lock = new ReentrantLock();
    Runnable rab = new Runnable() {

        @Override
        public void run() {
            try {
                sch.getResources();
            //					sch.getResourcesExt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Thread tha = new Thread(rab);
    tha.start();
    tha.wait();
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				try {
//					sch.getResources();
////					sch.getResourcesExt();
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} 
//				
//			}
//		}).start();
}
Example 59
Project: nebula-master  File: ThermometerExample.java View source code
public static void main(String[] args) {
    final Shell shell = new Shell();
    shell.setSize(300, 250);
    shell.open();
    //use LightweightSystem to create the bridge between SWT and draw2D
    final LightweightSystem lws = new LightweightSystem(shell);
    //Create widget
    final ThermometerFigure thermo = new ThermometerFigure();
    //Init widget
    thermo.setBackgroundColor(XYGraphMediaFactory.getInstance().getColor(255, 255, 255));
    thermo.setBorder(new SchemeBorder(SchemeBorder.SCHEMES.ETCHED));
    thermo.setRange(-100, 100);
    thermo.setLoLevel(-50);
    thermo.setLoloLevel(-80);
    thermo.setHiLevel(60);
    thermo.setHihiLevel(80);
    thermo.setShowHi(false);
    thermo.setMajorTickMarkStepHint(50);
    lws.setContents(thermo);
    //Update the widget in another thread.
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    thermo.setValue(Math.sin(counter++ / 10.0) * 100);
                }
            });
        }
    }, 100, 100, TimeUnit.MILLISECONDS);
    Display display = Display.getDefault();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    future.cancel(true);
    scheduler.shutdown();
}
Example 60
Project: oddjob-master  File: OddjobServicesBean.java View source code
@Override
public String serviceNameFor(Class<?> theClass, String flavour) {
    if (theClass.isAssignableFrom(ClassLoader.class)) {
        return CLASSLOADER_SERVICE;
    } else if (theClass.isAssignableFrom(ExecutorService.class)) {
        return POOL_EXECUTOR;
    } else if (theClass.isAssignableFrom(ScheduledExecutorService.class)) {
        return SCHEDULED_EXECUTOR;
    } else if (theClass.isAssignableFrom(InputHandler.class)) {
        return INPUT_HANDLER;
    } else if (theClass.isAssignableFrom(OddjobServices.class)) {
        return ODDJOB_SERVICES;
    } else {
        return null;
    }
}
Example 61
Project: osgi-jax-rs-connector-master  File: ResourcePublisher_Test.java View source code
private ScheduledExecutorService createSameThreadExecutor() {
    ScheduledExecutorService executorService = mock(ScheduledExecutorService.class);
    doAnswer(new Answer<ScheduledFuture<?>>() {

        @Override
        public ScheduledFuture<?> answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = (Runnable) invocation.getArguments()[0];
            runnable.run();
            return future;
        }
    }).when(executorService).schedule(any(Runnable.class), anyLong(), eq(TimeUnit.MILLISECONDS));
    return executorService;
}
Example 62
Project: owner-master  File: ScheduledExecutorServiceSpike.java View source code
public static void main(String[] args) throws InterruptedException {
    ThreadFactory tf = new ThreadFactory() {

        public Thread newThread(Runnable r) {
            try {
                Thread result = new Thread(r);
                result.setDaemon(true);
                return result;
            } finally {
                System.out.println("new thread created");
            }
        }
    };
    ScheduledExecutorService stp = Executors.newSingleThreadScheduledExecutor(tf);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            if (count++ % 2 == 0)
                System.out.printf("*");
        }
    }, 500, 500, TimeUnit.MILLISECONDS);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            ++count;
            if (count != 5 && count != 10)
                System.out.printf(".");
            if (count == 10)
                count = 0;
        }
    }, 100, 100, TimeUnit.MILLISECONDS);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            System.out.print(++count);
        }
    }, 1000, 1000, TimeUnit.MILLISECONDS);
    Thread.sleep(10000L);
}
Example 63
Project: palava-concurrent-master  File: BackgroundSchedulerModule.java View source code
@Override
@SuppressWarnings("deprecation")
public void configure(Binder binder) {
    binder.install(new SchedulerModule(BackgroundScheduler.class, BackgroundScheduler.NAME));
    final Key<ScheduledExecutorService> key = Key.get(ScheduledExecutorService.class, BackgroundScheduler.class);
    binder.bind(Executor.class).annotatedWith(Background.class).to(key).in(Singleton.class);
    binder.bind(ExecutorService.class).annotatedWith(Background.class).to(key).in(Singleton.class);
    binder.bind(ScheduledExecutorService.class).annotatedWith(Background.class).to(key).in(Singleton.class);
}
Example 64
Project: parseq-master  File: AbstractExample.java View source code
public void runExample() throws Exception {
    _serviceScheduler = Executors.newScheduledThreadPool(2);
    final int numCores = Runtime.getRuntime().availableProcessors();
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(numCores + 1);
    final Engine engine = new EngineBuilder().setTaskExecutor(scheduler).setTimerScheduler(scheduler).build();
    try {
        doRunExample(engine);
    } finally {
        engine.shutdown();
        scheduler.shutdownNow();
        _serviceScheduler.shutdown();
        _serviceScheduler = null;
    }
}
Example 65
Project: rest.li-master  File: PropertyEventBusImplTest.java View source code
@Override
public PropertyEventBus<String> getBus() {
    // TODO rewrite tests in the parent class so they work with either sync or async, and
    // test both modes of operation.
    ScheduledExecutorService executorService = new SynchronousExecutorService();
    PropertyEventPublisher<String> publisher = new MockStore<String>();
    PropertyEventBus<String> bus = new PropertyEventBusImpl<String>(executorService, publisher);
    return bus;
}
Example 66
Project: RocketMQ-3.0.8-master  File: SystemClock.java View source code
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, precision, precision, TimeUnit.MILLISECONDS);
}
Example 67
Project: rrd4j-master  File: RrdNioBackendTest.java View source code
@Test
public void testBackendFactoryWithExecutor() throws IOException {
    RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    factory.setSyncThreadPool(new RrdSyncThreadPool());
    File rrdfile = testFolder.newFile("testfile");
    RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
    be.setLength(10);
    be.writeDouble(0, 0);
    be.close();
    executor.shutdown();
    DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
    Double d = is.readDouble();
    Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
    is.close();
}
Example 68
Project: servo-master  File: PollSchedulerTest.java View source code
@Test
public void testStop() throws Exception {
    ScheduledExecutorService s = Executors.newScheduledThreadPool(2);
    PollScheduler.getInstance().start(s);
    assertTrue(PollScheduler.getInstance().isStarted());
    PollScheduler.getInstance().stop();
    assertTrue(!PollScheduler.getInstance().isStarted());
    assertTrue(s.isShutdown());
}
Example 69
Project: siddhi-master  File: SchedulerParser.java View source code
/**
     * Create Scheduler object based on the execution plan playback configuration.
     *
     * @param scheduledExecutorService ScheduledExecutorService
     * @param singleThreadEntryValve   Schedulable
     * @param executionPlanContext     ExecutionPlanContext
     * @return Scheduler instance
     */
public static Scheduler parse(ScheduledExecutorService scheduledExecutorService, Schedulable singleThreadEntryValve, ExecutionPlanContext executionPlanContext) {
    Scheduler scheduler;
    if (executionPlanContext.isPlayback()) {
        // Playback mode is enabled
        scheduler = new EventTimeBasedScheduler(singleThreadEntryValve, executionPlanContext);
    } else {
        // Default execution
        scheduler = new SystemTimeBasedScheduler(executionPlanContext.getScheduledExecutorService(), singleThreadEntryValve, executionPlanContext);
    }
    return scheduler;
}
Example 70
Project: simplejavayoutubeuploader-master  File: ThumbnailPostProcessor.java View source code
@Override
public Upload process(final Upload upload) {
    if (null != upload.getThumbnail()) {
        final ScheduledExecutorService schedueler = Executors.newSingleThreadScheduledExecutor();
        final RetryExecutor executor = new AsyncRetryExecutor(schedueler).withExponentialBackoff(5000, 2).withMaxDelay(30000).withMaxRetries(10).retryOn(ThumbnailIOException.class).abortOn(FileNotFoundException.class);
        try {
            executor.doWithRetry(new RetryRunnable() {

                @Override
                public void run(final RetryContext retryContext) throws FileNotFoundException, ThumbnailIOException {
                    thumbnailService.upload(upload.getThumbnail(), upload.getVideoid(), upload.getAccount());
                }
            });
        } catch (final Exception e) {
            LOGGER.error("Thumbnail IOException", e);
        } finally {
            schedueler.shutdown();
        }
    }
    return upload;
}
Example 71
Project: SlyceMessaging-master  File: ScrollUtils.java View source code
public static void scrollToPositionAfterDelay(final int position, final RecyclerView mRecyclerView, final RecyclerView.Adapter mRecyclerAdapter) {
    ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
    scheduleTaskExecutor.schedule(new Runnable() {

        @Override
        public void run() {
            scrollToPosition(position + 1, mRecyclerView, mRecyclerAdapter);
        }
    }, 150, TimeUnit.MILLISECONDS);
}
Example 72
Project: spring-mvc-qq-weibo-master  File: SimpleJobDispatcherDemo.java View source code
private static void startPrintStatistics(final JobStatistics statistics) {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    statisticsTask = scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            System.out.printf("Scheduled job %d, Ready Job %d, Dispatch Counter %d%n", statistics.getScheduledJobNumber(), statistics.getReadyJobNumber(), statistics.getDispatchCounter());
        }
    }, 0, 10, TimeUnit.SECONDS);
}
Example 73
Project: telemetry-master  File: ExampleService.java View source code
@Override
public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
    Client client = new JerseyClientBuilder().using(environment).using(configuration.getProxyClient()).build();
    environment.addResource(new ProxyResource(client));
    ScheduledExecutorService executorService = environment.managedScheduledExecutorService("delayed-tasks", 5);
    final NapDAO napDAO = new NapDAO(hibernate.getSessionFactory());
    environment.addResource(new NapResource(napDAO));
    environment.addResource(new NapsResource(napDAO));
    environment.addResource(new DelayedWriteResource(napDAO, executorService));
}
Example 74
Project: threadly-master  File: SingleThreadSchedulerServiceWrapperTest.java View source code
@Test
// must be overridden because we can only do this test with one task for the single threaded version
@Override
public void scheduleAtFixedRateTest() {
    ScheduledExecutorService scheduler = makeScheduler(1);
    try {
        // execute a task first in case there are any initial startup actions which may be slow
        scheduler.execute(DoNothingRunnable.instance());
        TestRunnable tr = new TestRunnable(DELAY_TIME - 1);
        scheduler.scheduleAtFixedRate(tr, 0, DELAY_TIME, TimeUnit.MILLISECONDS);
        tr.blockTillFinished((DELAY_TIME * (CYCLE_COUNT - 1)) + 2000, CYCLE_COUNT);
        long executionDelay = tr.getDelayTillRun(CYCLE_COUNT);
        assertTrue(executionDelay >= DELAY_TIME * (CYCLE_COUNT - 1));
        // should be very timely with a core pool size that matches runnable count
        assertTrue(executionDelay <= (DELAY_TIME * (CYCLE_COUNT - 1)) + (SLOW_MACHINE ? 2000 : 1000));
    } finally {
        scheduler.shutdownNow();
    }
}
Example 75
Project: tomee-master  File: ManagedScheduledExecutorServiceImplFactory.java View source code
private ScheduledExecutorService createScheduledExecutorService() {
    ManagedThreadFactory managedThreadFactory;
    try {
        managedThreadFactory = ThreadFactories.findThreadFactory(threadFactory);
    } catch (final Exception e) {
        Logger.getInstance(LogCategory.OPENEJB, ManagedScheduledExecutorServiceImplFactory.class).warning("Unable to create configured thread factory: " + threadFactory, e);
        managedThreadFactory = new ManagedThreadFactoryImpl();
    }
    return new ScheduledThreadPoolExecutor(core, managedThreadFactory, CURejectHandler.INSTANCE);
}
Example 76
Project: udidb-master  File: InMemoryConnector.java View source code
@Override
public IPendingWampConnection connect(ScheduledExecutorService scheduler, IPendingWampConnectionListener connectListener, IWampConnectionListener clientConnectionListener) {
    IWampConnectionListener routerConnectionListener = wampRouter.connectionAcceptor().createNewConnectionListener();
    InMemoryConnection routerConnection = new InMemoryConnection(clientConnectionListener);
    wampRouter.connectionAcceptor().acceptNewConnection(routerConnection, routerConnectionListener);
    InMemoryConnection clientConnection = new InMemoryConnection(routerConnectionListener);
    connectListener.connectSucceeded(clientConnection);
    return () -> {
        // This should never occur because the connection is immediately established
        connectListener.connectFailed(new IllegalStateException());
    };
}
Example 77
Project: weiciyuan-master  File: CrashManager.java View source code
public static void registerHandler() {
    Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    // Register if not already registered
    if (!(currentHandler instanceof ExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(currentHandler));
    }
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutorService.schedule(new ClearLogTask(), 5, TimeUnit.SECONDS);
}
Example 78
Project: wicket-examples-master  File: WicketApplication.java View source code
@Override
public void init() {
    super.init();
    eventBus = new EventBus(this);
    eventBus.getParameters().setTransport(AtmosphereTransport.STREAMING);
    eventBus.getParameters().setLogLevel(AtmosphereLogLevel.DEBUG);
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    final Runnable beeper = new Runnable() {

        @Override
        public void run() {
            try {
                eventBus.post(new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    scheduler.scheduleWithFixedDelay(beeper, 2, 2, TimeUnit.SECONDS);
}
Example 79
Project: wildfly-swarm-master  File: TempFileProviderProducer.java View source code
@PostConstruct
void init() {
    File serverTmp;
    try {
        serverTmp = TempFileManager.INSTANCE.newTempDirectory(TEMP_DIR_NAME, ".d");
        System.setProperty("jboss.server.temp.dir", serverTmp.getAbsolutePath());
        ScheduledExecutorService tempFileExecutor = Executors.newSingleThreadScheduledExecutor();
        this.tempFileProvider = TempFileProvider.create(TEMP_DIR_NAME, tempFileExecutor, true);
    } catch (IOException e) {
        SwarmMessages.MESSAGES.errorSettingUpTempFileProvider(e);
    }
}
Example 80
Project: zookeeper-lite-master  File: SimpleSessionExecutor.java View source code
public static ParameterizedFactory<Session, SimpleSessionExecutor> factory(final ScheduledExecutorService scheduler, final Supplier<? extends TaskExecutor<? super SessionOperation.Request<?>, Message.ServerResponse<?>>> server) {
    checkNotNull(scheduler);
    checkNotNull(server);
    return new ParameterizedFactory<Session, SimpleSessionExecutor>() {

        @Override
        public SimpleSessionExecutor get(Session value) {
            Automatons.SynchronizedEventfulAutomaton<ProtocolState, Object, ?> automaton = Automatons.createSynchronizedEventful(Automatons.createEventful(Automatons.createLogging(LogManager.getLogger(SimpleSessionExecutor.class), ProtocolMessageAutomaton.asAutomaton(ProtocolState.CONNECTED))));
            return new SimpleSessionExecutor(value, automaton, new StrongConcurrentSet<SessionListener>(), scheduler, server.get());
        }
    };
}
Example 81
Project: alfa-master  File: Alfa.java View source code
public void fetchAndStoreLogs(List<LogFetcher> logFetchers, LogCleaner logCleaner) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(logFetchers.size());
    //the next start will be blocked until the first one has finished 
    for (LogFetcher logFetcher : logFetchers) {
        scheduledExecutorService.scheduleAtFixedRate(logFetcher, 0, logFetcher.getPollingIntervalMinutes(), TimeUnit.MINUTES);
    }
    //this will execute the logCleaner every 24 hours
    scheduledExecutorService.scheduleAtFixedRate(logCleaner, 0, 24, TimeUnit.HOURS);
}
Example 82
Project: Amoeba-Plus-For-MySQL-master  File: Crontab.java View source code
@Override
public void run() {
    while (true) {
        try {
            future.get();
        // 请��在这里添加其他代�,
        // 因为会future会将控制�转给ScheduledExecutorService
        // 这里永远�会被执行到
        } catch (Exception e) {
            logger.error("Exception thrown in Cron task, try to recover, task name: " + (task == null ? "null" : task.getClass()));
            future.cancel(true);
            int i = retryTimesCounter.incrementAndGet();
            if (i <= MAX_RETRY_TIMES) {
                if (!service.isShutdown() && !service.isTerminated()) {
                    boolean isStartRightNow = false;
                    startRuleConfigUpdateSchedule(service, task, retryTimesCounter, RELOAD_DELAY, MAX_RETRY_TIMES, isStartRightNow);
                }
            } else {
                logger.error("I have try my best to recover, but it doesn't work, task " + (task == null ? "null" : task.getClass()) + " fail");
                service.shutdown();
            }
            return;
        }
    }
}
Example 83
Project: cassandra-cqlMod-master  File: ComitLogStress.java View source code
public static void main(String[] args) throws Exception {
    int NUM_THREADS = Runtime.getRuntime().availableProcessors();
    if (args.length >= 1) {
        NUM_THREADS = Integer.parseInt(args[0]);
        System.out.println("Setting num threads to: " + NUM_THREADS);
    }
    ExecutorService executor = new JMXEnabledThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10 * NUM_THREADS), new NamedThreadFactory(""), "");
    ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
    org.apache.cassandra.SchemaLoader.loadSchema();
    final AtomicLong count = new AtomicLong();
    final long start = System.currentTimeMillis();
    System.out.println(String.format(format, "seconds", "max_mb", "allocated_mb", "free_mb", "diffrence", "count"));
    scheduled.scheduleAtFixedRate(new Runnable() {

        long lastUpdate = 0;

        public void run() {
            Runtime runtime = Runtime.getRuntime();
            long maxMemory = mb(runtime.maxMemory());
            long allocatedMemory = mb(runtime.totalMemory());
            long freeMemory = mb(runtime.freeMemory());
            long temp = count.get();
            System.out.println(String.format(format, ((System.currentTimeMillis() - start) / 1000), maxMemory, allocatedMemory, freeMemory, (temp - lastUpdate), lastUpdate));
            lastUpdate = temp;
        }
    }, 1, 1, TimeUnit.SECONDS);
    while (true) {
        executor.execute(new CommitlogExecutor());
        count.incrementAndGet();
    }
}
Example 84
Project: cettia-examples-master  File: Bootstrap.java View source code
@Override
public void contextInitialized(ServletContextEvent event) {
    final Server server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {

        @Override
        public void on(final ServerSocket socket) {
            socket.on("echo", new Action<Object>() {

                @Override
                public void on(Object data) {
                    System.out.println("on echo event: " + data);
                    socket.send("echo", data);
                }
            });
            socket.on("chat", new Action<Object>() {

                @Override
                public void on(Object data) {
                    System.out.println("on chat event: " + data);
                    server.all().send("chat", data);
                }
            });
        }
    });
    HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);
    ServletContext context = event.getServletContext();
    Servlet servlet = new AsityAtmosphereServlet().onhttp(httpTransportServer).onwebsocket(wsTransportServer);
    ServletRegistration.Dynamic reg = context.addServlet(AsityAtmosphereServlet.class.getName(), servlet);
    reg.setAsyncSupported(true);
    reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
    reg.addMapping("/cettia");
    // Put server into application scope for JAX-RS resource to use it.
    // Otherwise, use dependency-injection service
    context.setAttribute(Server.class.getName(), server);
    // To test it's working, trigger JAX-RS resource every 3 seconds
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            tick();
        }
    }, 0, 3, TimeUnit.SECONDS);
}
Example 85
Project: citizen-complaint-master  File: CitizenComplaintApplication.java View source code
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onCreate() {
    if (CitizenComplaintConstants.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
    }
    super.onCreate();
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    executorService.scheduleWithFixedDelay(new CitizenComplaintPostDetailsTask(), 1, 2 * 60, TimeUnit.SECONDS);
    initImageLoader(getApplicationContext());
}
Example 86
Project: cloudtm-data-platform-master  File: ReplQueueRestartTest.java View source code
@SuppressWarnings("unchecked")
public void testReplQueueImpl() {
    ReplicationQueueImpl rqi = new ReplicationQueueImpl();
    ScheduledFuture sf = mock(ScheduledFuture.class);
    when(sf.cancel(eq(true))).thenReturn(true);
    ScheduledExecutorService ses = mock(ScheduledExecutorService.class);
    when(ses.scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))).thenReturn(sf);
    RpcManager rpc = mock(RpcManager.class);
    CommandsFactory commandsFactory = mock(CommandsFactory.class);
    Configuration c = new Configuration();
    c.setUseReplQueue(true);
    rqi.injectDependencies(ses, rpc, c, commandsFactory);
    rqi.start();
    rqi.stop();
}
Example 87
Project: contrail-vcenter-plugin-master  File: TaskWatchDogTest.java View source code
@Test
public void test1() {
    latch = new CountDownLatch(TASK_COUNT);
    ScheduledExecutorService ex = Executors.newScheduledThreadPool(TASK_COUNT);
    MonitoredTaskTest tasks[] = new MonitoredTaskTest[TASK_COUNT];
    List<Future<?>> futures = new ArrayList<Future<?>>();
    for (int i = 0; i < TASK_COUNT; i++) {
        tasks[i] = new MonitoredTaskTest(0);
        futures.add(ex.submit(tasks[i]));
    }
    try {
        // wait for all the tasks to get blocked
        latch.await();
    } catch (InterruptedException e) {
        assertTrue("Task interrupted " + e.getMessage(), false);
        e.printStackTrace();
    }
    for (Future<?> future : futures) {
        assertFalse(future.isDone());
    }
    // launch watch dogs
    ScheduledExecutorService watchDogExecutor = Executors.newScheduledThreadPool(2);
    List<Future<?>> futuresAker = new ArrayList<Future<?>>();
    for (Runnable aker : TaskWatchDog.values()) {
        futuresAker.add(watchDogExecutor.schedule(aker, 0, TimeUnit.SECONDS));
    }
    // wait for watch dogs to finish running
    for (Future<?> future : futuresAker) {
        try {
            future.get();
        } catch (InterruptedException e1) {
            assertTrue("Watchdogs interrupted " + e1.getMessage(), false);
            e1.printStackTrace();
        } catch (ExecutionException e2) {
            assertTrue("Watchdogs execution exception " + e2.getMessage(), false);
            e2.printStackTrace();
        }
    }
    for (Future<?> future : futuresAker) {
        assertTrue(future.isDone());
    }
    for (TaskWatchDog aker : TaskWatchDog.values()) {
        assertNotEquals(aker.monitored, null);
    }
    assertFalse(TaskWatchDog.getMonitoredTasks().isEmpty());
    for (ConcurrentHashMap.Entry<Runnable, MonitoredTaskRecord> entry : TaskWatchDog.getMonitoredTasks().entrySet()) {
        MonitoredTaskRecord tRec = entry.getValue();
        assertTrue(tRec.blocked);
    }
    for (MonitoredTaskTest task : tasks) {
        assertTrue(TaskWatchDog.getMonitoredTasks().containsKey(task));
    }
}
Example 88
Project: controller-master  File: TestingScheduledThreadPoolModule.java View source code
@Override
protected AutoCloseable prepareMockedInstance() throws Exception {
    ScheduledThreadPoolWrapper instance = mock(ScheduledThreadPoolWrapper.class);
    ScheduledExecutorService ses = mock(ScheduledExecutorService.class);
    {
        // mockFuture
        ScheduledFuture<?> future = mock(ScheduledFuture.class);
        doReturn(false).when(future).cancel(anyBoolean());
        try {
            doReturn(mock(Object.class)).when(future).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        doReturn(future).when(ses).schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class));
        doReturn(future).when(ses).scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class));
    }
    doNothing().when(ses).execute(any(Runnable.class));
    doNothing().when(ses).execute(any(ListenableFutureTask.class));
    doReturn(ses).when(instance).getExecutor();
    doNothing().when(instance).close();
    doReturn(1).when(instance).getMaxThreadCount();
    return instance;
}
Example 89
Project: dropwizard-etcd-master  File: EtcdWatchServiceRule.java View source code
@Override
public void evaluate() throws Throwable {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ObjectMapper mapper = new ObjectMapper();
    try {
        try {
            clientSupplier.get().deleteDir(directory).recursive().send().get();
        } catch (Exception e) {
            System.out.printf("could not delete %s from service rule", directory);
            e.printStackTrace();
        }
        service = WatchService.builder().withEtcdClient(clientSupplier).withDirectory(directory).withExecutor(executor).withMapper(mapper).withMetricRegistry(new MetricRegistry()).withWatchTimeout(10, TimeUnit.MILLISECONDS).build();
        service.start();
        try {
            base.evaluate();
        } finally {
            try {
                service.stop();
            } catch (Throwable ioe) {
                ioe.printStackTrace(System.err);
            }
            service = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        executor.shutdown();
    }
}
Example 90
Project: dropwizard-master  File: LifecycleEnvironmentTest.java View source code
@Test
public void scheduledExecutorServiceThreadFactory() throws ExecutionException, InterruptedException {
    final String expectedName = "DropWizard ThreadFactory Test";
    final String expectedNamePattern = expectedName + "-%d";
    final ThreadFactory tfactory = (new ThreadFactoryBuilder()).setDaemon(false).setNameFormat(expectedNamePattern).build();
    final ScheduledExecutorService executorService = environment.scheduledExecutorService("DropWizard Service", tfactory).build();
    final Future<Boolean> isFactoryInUse = executorService.submit(() -> Thread.currentThread().getName().startsWith(expectedName));
    assertThat(isFactoryInUse.get()).isTrue();
}
Example 91
Project: EasySendToKindle-master  File: TimeDialog.java View source code
/**
	 * ´´½¨Ò»¸ö¶¨Ê±¹Ø±Õ´°¿Ú²¢·µ»Ø½á¹û¡£
	 * @param father ¸¸¶ÔÏó
	 * @param message ÌáʾÐÅÏ¢
	 * @param sec µÈ´ýÃëÊý
	 * @return
	 */
public int showDialog(JFrame father, String message, int sec) {
    this.message = message;
    secends = sec;
    label.setText(message);
    label.setBounds(80, 6, 200, 20);
    ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
    confirm = new JButton("È·ÈÏ");
    confirm.setBounds(100, 40, 60, 20);
    confirm.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            result = OK_BUTTON;
            TimeDialog.this.dialog.dispose();
        }
    });
    cancel = new JButton("È¡Ïû");
    cancel.setBounds(190, 40, 60, 20);
    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            result = NO_BUTTON;
            TimeDialog.this.dialog.dispose();
        }
    });
    dialog = new JDialog(father, true);
    dialog.setTitle("±¾´°¿Ú½«ÔÚ" + secends + "Ãëºó×Ô¶¯¹Ø±Õ");
    dialog.setLayout(null);
    dialog.add(label);
    dialog.add(confirm);
    dialog.add(cancel);
    s.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            TimeDialog.this.secends--;
            if (TimeDialog.this.secends == 0) {
                result = TIMEOUT;
                TimeDialog.this.dialog.dispose();
            } else {
                dialog.setTitle("±¾´°¿Ú½«ÔÚ" + secends + "Ãëºó×Ô¶¯¹Ø±Õ");
            }
        }
    }, 1, 1, TimeUnit.SECONDS);
    dialog.pack();
    dialog.setSize(new Dimension(350, 100));
    dialog.setLocationRelativeTo(father);
    dialog.setVisible(true);
    return result;
}
Example 92
Project: EasyTransaction-master  File: TransactionLogCleanJob.java View source code
@PostConstruct
public void init() {
    String days = config.getExtendConfig("translog.clean.before.days");
    if (StringUtils.isEmpty(days)) {
        LOG.warn("translog.clean.before.days not set. do not execute clean job");
        return;
    }
    String cleanTime = config.getExtendConfig("translog.clean.time").trim();
    final Integer cleanLogDaysRestriction = Integer.valueOf(days);
    Date nextExeucteTime = calcNextExecuteTime(cleanTime);
    long initialDelay = nextExeucteTime.getTime() - System.currentTimeMillis();
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("CleanLogJob", true));
    executor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                if (master.hasLeaderShip()) {
                    Calendar instance = Calendar.getInstance();
                    instance.add(Calendar.DATE, -cleanLogDaysRestriction);
                    LOG.info("START CLEAN EXPIRED TRANSACTION LOGS.DAYS:" + cleanLogDaysRestriction);
                    logWritter.cleanFinishedLogs(config.getAppId(), instance.getTime());
                    LOG.info("END CLEAN EXPIRED TRANSACTION LOGS.DAYS");
                } else {
                    LOG.info("NOT MASTER,do not execute transaction log clean job");
                }
            } catch (Exception e) {
                LOG.error("execute clean job error!", e);
            }
        }
    }, initialDelay, 24l * 60 * 60 * 1000, TimeUnit.MILLISECONDS);
}
Example 93
Project: effektif-master  File: AsynchronousExecutorService.java View source code
@Override
public void shutdown() {
    if (executor instanceof ScheduledExecutorService) {
        if (!((ScheduledExecutorService) executor).isShutdown()) {
            try {
                ScheduledExecutorService scheduledExecutorService = (ScheduledExecutorService) executor;
                if (log.isDebugEnabled())
                    log.debug("shutting down executor " + executor);
                scheduledExecutorService.shutdown();
                scheduledExecutorService.awaitTermination(shutdownTimeout, shutdownTimeUnit);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 94
Project: elasticsearch-gatherer-master  File: GathererService.java View source code
@Override
protected void doStart() throws ElasticSearchException {
    // announce default gatherers
    announceGatherers();
    // the load updater task
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(daemonThreadFactory(settings, "gatherer_load_watcher"));
    executorService.scheduleAtFixedRate(new Thread() {

        public void run() {
            double load = operatingSystemMXBean.getSystemLoadAverage();
            nodeService.putAttribute(GathererConstants.GATHERER_LOAD, Double.toString(load));
        }
    }, 1L, 1L, TimeUnit.MINUTES);
    // the queue length updater task
    executorService.scheduleAtFixedRate(new Thread() {

        public void run() {
            // TODO getPendingJobs();
            int length = 0;
            nodeService.putAttribute(GathererConstants.GATHERER_LENGTH, Integer.toString(length));
        }
    }, 1L, 5L, TimeUnit.SECONDS);
    logger.info("started");
}
Example 95
Project: flink-master  File: TimerServiceTest.java View source code
/**
	 * Test all timeouts registered can be unregistered
	 * @throws Exception
   */
@Test
@SuppressWarnings("unchecked")
public void testUnregisterAllTimeouts() throws Exception {
    // Prepare all instances.
    ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
    ScheduledFuture scheduledFuture = mock(ScheduledFuture.class);
    when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(scheduledFuture);
    TimerService<AllocationID> timerService = new TimerService<>(scheduledExecutorService, 100L);
    TimeoutListener<AllocationID> listener = mock(TimeoutListener.class);
    timerService.start(listener);
    // Invoke register and unregister.
    timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);
    timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);
    timerService.unregisterAllTimeouts();
    // Verify.
    Map<?, ?> timeouts = (Map<?, ?>) Whitebox.getInternalState(timerService, "timeouts");
    assertTrue(timeouts.isEmpty());
    verify(scheduledFuture, times(2)).cancel(true);
}
Example 96
Project: framework-master  File: NoLayoutUpdateWhichNeedsLayout.java View source code
protected void scheduleTask() {
    Thread t = new Thread() {

        @Override
        public void run() {
            getUI().access(new Runnable() {

                @Override
                public void run() {
                    updateProgresBar(50);
                }
            });
        }
    };
    ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
    worker.schedule(t, 2, TimeUnit.SECONDS);
}
Example 97
Project: Giraffe-master  File: MockCommandFuture.java View source code
/**
     * This method will asynchronous fail the CommandFuture after a given period
     * of time simulating a scenario where there was an IOException or an error
     * during computation.
     *
     * @param exception The exception to fail the CommandFuture with
     * @param afterThisManyMillis The number of milliseconds to wait before
     *        failing the CommandFuture
     */
public void failWithException(final Exception exception, long afterThisManyMillis) {
    if (afterThisManyMillis == 0) {
        setException(exception);
        return;
    }
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.schedule(new Runnable() {

        @Override
        public void run() {
            setException(exception);
        }
    }, afterThisManyMillis, TimeUnit.MILLISECONDS);
    executor.shutdown();
}
Example 98
Project: glowroot-master  File: ScheduledRunnableTest.java View source code
@Before
@SuppressWarnings("unchecked")
public void beforeEachTest() {
    scheduledExecutorService = mock(ScheduledExecutorService.class);
    when(scheduledExecutorService.scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))).thenReturn(mock(ScheduledFuture.class));
    when(scheduledExecutorService.scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))).thenReturn(mock(ScheduledFuture.class));
}
Example 99
Project: graylog2-server-master  File: SchedulerBindings.java View source code
@Override
protected void configure() {
    // TODO Add instrumentation to ExecutorService and ThreadFactory
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(SCHEDULED_THREADS_POOL_SIZE, new ThreadFactoryBuilder().setNameFormat("scheduled-%d").setDaemon(false).setUncaughtExceptionHandler(new Tools.LogUncaughtExceptionHandler(LOG)).build());
    bind(ScheduledExecutorService.class).annotatedWith(Names.named("scheduler")).toInstance(scheduler);
    // TODO Add instrumentation to ExecutorService and ThreadFactory
    final ScheduledExecutorService daemonScheduler = Executors.newScheduledThreadPool(SCHEDULED_THREADS_POOL_SIZE, new ThreadFactoryBuilder().setNameFormat("scheduled-daemon-%d").setDaemon(true).setUncaughtExceptionHandler(new Tools.LogUncaughtExceptionHandler(LOG)).build());
    bind(ScheduledExecutorService.class).annotatedWith(Names.named("daemonScheduler")).toInstance(daemonScheduler);
    bind(Periodicals.class).toInstance(new Periodicals(scheduler, daemonScheduler));
}
Example 100
Project: guide-master  File: Executors3.java View source code
private static void test3() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    Runnable task = () -> {
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("Scheduling: " + System.nanoTime());
        } catch (InterruptedException e) {
            System.err.println("task interrupted");
        }
    };
    executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
}
Example 101
Project: ignite-master  File: AgentDemoUtils.java View source code
/**
     * Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
     *
     * @param corePoolSize Number of threads to keep in the pool, even if they are idle.
     * @param threadName Part of thread name that would be used by thread factory.
     * @return Newly created scheduled thread pool.
     */
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, final String threadName) {
    ScheduledExecutorService srvc = Executors.newScheduledThreadPool(corePoolSize, new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, String.format("%s-%d", threadName, THREAD_CNT.getAndIncrement()));
            thread.setDaemon(true);
            return thread;
        }
    });
    ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) srvc;
    // Setting up shutdown policy.
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    return srvc;
}