Example usage for java.util.concurrent Executors newScheduledThreadPool

List of usage examples for java.util.concurrent Executors newScheduledThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newScheduledThreadPool.

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testMailSendException() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();/*from   w ww. jav a2s  . c  o m*/
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, true);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, never()).sendMessage(eq(2L));
    verify(mailSendHandler, never()).sendMessage(eq(3L));
}

From source file:stargate.drivers.hazelcast.schedule.HazelcastScheduleDriver.java

@Override
public synchronized void startDriver() throws IOException {
    try {// w  ww .j a v a 2  s . com
        this.driverGroup = HazelcastCoreDriver.getInstance();
    } catch (DriverNotInstantiatedException ex) {
        throw new IOException(ex);
    }

    this.taskThreads = this.config.getTaskThreads();
    this.threadPool = Executors.newScheduledThreadPool(this.taskThreads);
}

From source file:org.apache.hama.bsp.BSPTask.java

public BSPTask(BSPJobID jobId, String jobFile, TaskAttemptID taskid, int partition, String splitClass,
        BytesWritable split) {//  w  w w  . jav a  2s  .  co  m
    this.jobId = jobId;
    this.jobFile = jobFile;
    this.taskId = taskid;
    this.partition = partition;

    this.splitClass = splitClass;
    this.split = split;

    this.pingService = Executors.newScheduledThreadPool(1);
}

From source file:org.wicketstuff.nashorn.resource.NashornResourceReference.java

/**
 * Creates a nashorn resource reference with the given name
 * /*from   w ww  . ja v  a2  s.  c o  m*/
 * @param name
 *            the name of the nashorn resource reference
 * @param coreSize
 *            the core size of the script execution pool
 * @param delay
 *            the delay until a script execution is going to be terminated
 * @param delayUnit
 *            the unit until a script execution is going to be terminated
 * @param wait
 *            how long to w8 until the next memory check occurs
 * @param waitUnit
 *            the unit until the next memory check occurs
 * @param maxScriptMemorySize
 *            the memory usage the script process should use - else it will be aborted
 */
public NashornResourceReference(String name, int coreSize, long delay, TimeUnit delayUnit, long wait,
        TimeUnit waitUnit, long maxScriptMemorySize) {
    super(name);
    scheduledExecutorService = Executors.newScheduledThreadPool(coreSize);
    this.delay = delay;
    this.delayUnit = delayUnit;
    this.wait = wait;
    this.waitUnit = waitUnit;
    this.maxScriptMemorySize = maxScriptMemorySize;
}

From source file:io.fabric8.forge.ipaas.repository.NexusConnectionRepository.java

@PostConstruct
public void start() {
    if (started.compareAndSet(false, true)) {
        System.out.println("NexusConnectionRepository is already started");
        return;//  ww  w.  ja v  a2s.  co m
    }

    System.out.println("Starting NexusConnectionRepository");

    if (nexusUrl == null || nexusUrl.isEmpty()) {
        System.out.println("Nexus service not found. Indexing Nexus is not enabled!");
        return;
    }

    System.out.println("Indexing Nexus every " + delay + " seconds interval");
    executorService = Executors.newScheduledThreadPool(1);

    executorService.scheduleWithFixedDelay(() -> {
        try {
            System.out.println("Indexing Nexus " + nexusUrl + " +++ start +++");
            indexNexus();
        } catch (Throwable e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);

            if (sw.toString().contains("UnknownHostException")) {
                // less noise if its unknown host
                System.err
                        .println("Error indexing Nexus " + nexusUrl + " due unknown hosts: " + e.getMessage());
            } else {
                System.err.println(
                        "Error indexing Nexus " + nexusUrl + " due " + e.getMessage() + "\n" + sw.toString());
            }
        } finally {
            System.out.println("Indexing Nexus " + nexusUrl + " +++ end +++");
        }
    }, 10, delay, TimeUnit.SECONDS);
}

From source file:com.zb.app.biz.service.impl.TravelCompanyServiceImpl.java

@PostConstruct
public void cronCache() {
    Result companyRegist = notifyService.regist(new NotifyListener() {

        @EventConfig(events = { EventType.companyAdd, EventType.companyDelete, EventType.companyUpdate })
        public void companyEvent(CompanyEvent event) {
            handle(event);/*from  w w  w  . j  a v  a  2 s  .co m*/
        }
    });
    if (companyRegist.isFailed()) {
        logger.error("TravelCompanyServiceImpl init companyRegist ?failed!");
    } else {
        logger.error("TravelCompanyServiceImpl init companyRegist ?success!");
    }

    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);
    newScheduledThreadPool.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                init();
            } catch (Throwable e) {
                logger.error("init travelCompanyCacheMap error", e);
            }
        }

    }, 0, 12, TimeUnit.HOURS);
}

From source file:com.dtstack.jlogstash.decoder.MultilineDecoder.java

public void init(String pattern, String what, InputQueueList queuelist) {

    if (pattern == null || what == null) {
        logger.error("pattern and what must not be null.");
        System.exit(-1);//  w ww .ja  va2s  .  c o m
    }

    if (!"previous".equals(what) && !"next".equals(what)) {
        logger.error("parameter what must in [previous, next]");
        System.exit(-1);
    }

    this.inputQueueList = queuelist;

    logger.warn("MultilineDecoder param pattern:{}, what:{}, negate:{}.",
            new Object[] { pattern, what, negate });

    this.pattern = pattern;
    this.what = what;

    patternReg = Pattern.compile(this.pattern);
    scheduleExecutor = Executors.newScheduledThreadPool(1);
    scheduleExecutor.scheduleWithFixedDelay(new FlushMonitor(), flushInterval, flushInterval,
            TimeUnit.MILLISECONDS);
}

From source file:org.apache.pulsar.io.hbase.sink.HbaseAbstractSink.java

@Override
public void open(Map<String, Object> config, SinkContext sinkContext) throws Exception {
    hbaseSinkConfig = HbaseSinkConfig.load(config);
    Preconditions.checkNotNull(hbaseSinkConfig.getZookeeperQuorum(), "zookeeperQuorum property not set.");
    Preconditions.checkNotNull(hbaseSinkConfig.getZookeeperClientPort(),
            "zookeeperClientPort property not set.");
    Preconditions.checkNotNull(hbaseSinkConfig.getZookeeperZnodeParent(),
            "zookeeperZnodeParent property not set.");
    Preconditions.checkNotNull(hbaseSinkConfig.getTableName(), "hbase tableName property not set.");

    getTable(hbaseSinkConfig);/*from w w  w.j av a2  s  .c o  m*/
    tableDefinition = getTableDefinition(hbaseSinkConfig);

    batchTimeMs = hbaseSinkConfig.getBatchTimeMs();
    batchSize = hbaseSinkConfig.getBatchSize();
    incomingList = Lists.newArrayList();
    flushExecutor = Executors.newScheduledThreadPool(1);
    flushExecutor.scheduleAtFixedRate(() -> flush(), batchTimeMs, batchTimeMs, TimeUnit.MILLISECONDS);
}

From source file:com.vmware.thinapp.manualmode.util.JobMonitorService.java

public JobMonitorService() {
    perfTasks = new ConcurrentHashMap<JobMonitorTicket, ScheduledFuture<?>>();
    executor = Executors.newScheduledThreadPool(MIN_PERF_TASK_THREADS);
}

From source file:org.tupelo_schneck.electric.ted.TedImporter.java

@Override
public void startup() {
    if (options.longImportInterval > 0) {
        longImportTask = repeatedlyImport(3600, true, options.longImportInterval);
    }//w ww .j a  v a  2  s.  c  o m
    if (options.importInterval > 0) {
        shortImportTask = repeatedlyImport(options.importInterval + options.importOverlap, false,
                options.importInterval);
    }
    if (options.voltAmpereImportIntervalMS > 0) {
        ExecutorService voltAmpereExecServ;
        if (options.kvaThreads == 0)
            voltAmpereExecServ = shortImportTask;
        else
            voltAmpereExecServ = Executors.newScheduledThreadPool(options.kvaThreads);
        voltAmpereImportTask = voltAmpereImporter(voltAmpereExecServ, options.voltAmpereImportIntervalMS);
    }
}