Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

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

Introduction

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

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor() 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:org.apache.hise.engine.HISESchedulerImpl.java

@PostConstruct
public void init() {
    executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleWithFixedDelay(jobExecutor, 1000, 1000, TimeUnit.MILLISECONDS);
}

From source file:playmidi.task.MidiPlayTaskTest.java

/**
 * Test of run method, of class MidiPlayTask.
 */// w w w. j av  a  2 s .  co m
@Test
public void testRun() throws IOException, FileNotFoundException, MidiUnavailableException,
        InvalidMidiDataException, InterruptedException {
    System.out.println("run");
    ScheduledExecutorService playerRunner = Executors.newSingleThreadScheduledExecutor();

    try (MidiPlayTask instance = new MidiPlayTask(name, count)) {
        playerRunner.execute(instance);
        Thread.sleep(20000);
        instance.stop();
    }
}

From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java

@Override
public void start(Map<String, String> props) {
    setConfigurationProperties(props);/*from  w  w  w . j a  va 2 s  .  co  m*/

    transferQueue = new LinkedTransferQueue<>();
    opcOperations = new SmartOpcOperations<>(createOpcOperations());
    ConnectionProfile connectionProfile = createConnectionProfile();
    host = connectionProfile.getConnectionUri().getHost();
    tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream()
            .collect(Collectors.toMap(TagInfo::getTagId, Function.identity()));
    minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval)
            .mapToLong(Duration::toMillis).min().getAsLong());
    opcOperations.connect(connectionProfile);
    if (!opcOperations.awaitConnected()) {
        throw new ConnectException("Unable to connect");
    }

    //set up polling source emission
    pollingScheduler = Executors.newSingleThreadScheduledExecutor();
    streamingThread = Executors.newSingleThreadExecutor();
    Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream()
            .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode()))
            .collect(Collectors.groupingBy(TagInfo::getSamplingInterval));
    final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>());
    pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> {
        final Instant now = Instant.now();
        v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull))
                .map(data -> Pair.of(now, data)).forEach(transferQueue::add);

    }, 0, k.toNanos(), TimeUnit.NANOSECONDS));
    //then subscribe for all
    final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration()
            .withDefaultSamplingInterval(Duration.ofMillis(10_000));
    tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration
            .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval()));
    running.set(true);
    streamingThread.submit(() -> {
        while (running.get()) {
            try {
                createSessionIfNeeded();
                if (session == null) {
                    return;
                }

                session.stream(subscriptionConfiguration,
                        tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> {
                            if (tagInfoMap.get(opcData.getTag()).getStreamingMode()
                                    .equals(StreamingMode.SUBSCRIBE)) {
                                transferQueue.add(Pair.of(
                                        hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(),
                                        opcData));
                            } else {
                                lastValues.put(opcData.getTag(), opcData);
                            }
                        });
            } catch (Exception e) {
                if (running.get()) {
                    logger.warn("Stream interrupted while reading from " + host, e);
                    safeCloseSession();
                    lastValues.clear();

                }
            }
        }
    });

}

From source file:net.sf.mpaxs.spi.computeHost.Host.java

/**
 * Meldet diesen Host beim Masterserver an. Nach erfolgreicher Anmeldung
 * kann der Masterserver Jobs an diesen Host vergeben.
 *//*from ww  w . j ava2s . c  o  m*/
private void connectToMasterServer() {
    final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    final long startUpAt = System.currentTimeMillis();
    final long failAfter = 5000;
    ses.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            Logger.getLogger(Host.class.getName()).log(Level.FINE,
                    "Trying to connect to MasterServer from IP " + settings.getLocalIp());
            long currentTime = System.currentTimeMillis();
            if (currentTime - startUpAt >= failAfter) {
                Logger.getLogger(Host.class.getName()).log(Level.WARNING,
                        "Waited {0} seconds for MasterServer, shutting down ComputeHost", (failAfter / 1000));
                System.exit(1);
            }
            try {
                Logger.getLogger(Host.class.getName()).log(Level.FINE,
                        "Trying to bind to MasterServer at " + settings.getMasterServerIP() + ":"
                                + settings.getMasterServerPort() + " with name: "
                                + settings.getMasterServerName());
                IRemoteServer remRef = (IRemoteServer) Naming.lookup("//" + settings.getMasterServerIP() + ":"
                        + settings.getMasterServerPort() + "/" + settings.getMasterServerName());
                settings.setRemoteReference(remRef);
                UUID hostID = remRef.addHost(authToken, settings.getName(), settings.getLocalIp(),
                        settings.getCores());
                settings.setHostID(hostID);
                Logger.getLogger(Host.class.getName()).log(Level.FINE, "Connection to server established!");
                ses.shutdown();
                try {
                    ses.awaitTermination(5, TimeUnit.SECONDS);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (NotBoundException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.INFO,
                        "Master server not found, waiting for connection!");
                //Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MalformedURLException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                System.exit(1);
            } catch (RemoteException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                System.exit(1);
            }
        }
    }, 1, settings.getMasterServerTimeout(), TimeUnit.SECONDS);

}

From source file:org.onebusaway.admin.service.server.impl.RssServiceAlertsSerivceImpl.java

@PostConstruct
public void start() throws Exception {
    if (_locale == null)
        _locale = Locale.getDefault();

    _executor = Executors.newSingleThreadScheduledExecutor();
    // re-build internal route cache
    _executor.scheduleAtFixedRate(new RefreshDataTask(), 0, 1, TimeUnit.HOURS);
    // poll feed after cache is built above
    _executor.scheduleAtFixedRate(new PollRssTask(), 1, 5, TimeUnit.MINUTES);
}

From source file:cn.leancloud.diamond.client.processor.LocalConfigInfoProcessor.java

public synchronized void start(String rootPath) {
    if (this.isRun) {
        return;//from www.ja  v a2s. com
    }
    this.rootPath = rootPath;
    this.isRun = true;
    if (this.singleExecutor == null || singleExecutor.isTerminated()) {
        singleExecutor = Executors.newSingleThreadScheduledExecutor();
    }
    initDataDir(rootPath);
    startCheckLocalDir(rootPath);
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

private void initCleanupThreads() {
    // Wrapper to lazily fetch the Registry object as this is not populated at instantiation time
    // Spin up a scheduled thread to poll for unused test runs and clean up them
    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new AutomationRunCleanupTask(this), 60L,
            60L, TimeUnit.SECONDS);
    // Spin up a scheduled thread to clean up and terminate nodes that were spun up
    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
            new AutomationNodeCleanupTask(this, ec2, requestMatcher), 60L, 15L, TimeUnit.SECONDS);
    // Spin up a scheduled thread to register unregistered dynamic nodes (will happen if hub gets shut down)
    Executors.newSingleThreadScheduledExecutor()
            .scheduleAtFixedRate(new AutomationOrphanedNodeRegistryTask(this), 1L, 5L, TimeUnit.MINUTES);
    // Spin up a scheduled thread to track nodes that are pending startup
    Executors.newSingleThreadScheduledExecutor()
            .scheduleAtFixedRate(new AutomationPendingNodeRegistryTask(this, ec2), 60L, 15L, TimeUnit.SECONDS);
    // Spin up a scheduled thread to analyzed queued requests to scale up capacity
    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new AutomationScaleNodeTask(this, ec2),
            60L, 15L, TimeUnit.SECONDS);
    String instanceId = System.getProperty(AutomationConstants.INSTANCE_ID);
    if (instanceId != null && instanceId.length() > 0) {
        log.info("Instance ID detected.  Hub termination thread will be started.");
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
                new AutomationHubCleanupTask(this, ec2, instanceId), 5L, 1L, TimeUnit.MINUTES);
    } else {/*from w w w  .j a  v a  2 s. c o  m*/
        log.info("Hub is not a dynamic hub -- termination logic will not be started");
    }
    String runReaperThread = System.getProperty(AutomationConstants.REAPER_THREAD_CONFIG);
    // Reaper thread defaults to on unless specified not to run
    if (!"false".equalsIgnoreCase(runReaperThread)) {
        // Spin up a scheduled thread to terminate orphaned instances
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new AutomationReaperTask(this, ec2),
                1L, 15L, TimeUnit.MINUTES);
    } else {
        log.info("Reaper thread not running due to config flag.");
    }
}

From source file:com.edmunds.etm.management.impl.ClientMonitor.java

@Override
public void afterPropertiesSet() throws Exception {

    // Set up the callback scheduler
    callbackScheduler = Executors.newSingleThreadScheduledExecutor();
    Runnable task = new ScheduledCallbackTask(clientIdlePeriod);
    long delay = SCHEDULER_EXECUTION_DELAY;
    long period = SCHEDULER_EXECUTION_PERIOD;
    callbackScheduler.scheduleAtFixedRate(task, delay, period, TimeUnit.MILLISECONDS);
}

From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceExportDialog.java

public WebServiceExportDialog(JuxtaAuthorFrame frame, WebServiceClient wsClient) {
    super(frame);
    this.juxtaFrame = frame;

    if (wsClient == null) {
        this.wsClient = new WebServiceClient(frame.getWebServiceUrl());
    } else {//  ww w  .  j ava2  s .  c o m
        this.wsClient = wsClient;
    }

    // size and title the main dialog body
    setTitle("Juxta Web Export");
    setResizable(false);
    setSize(495, 345);
    setLocationRelativeTo(getParent());
    ((JPanel) getContentPane()).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    getContentPane().setLayout(new BorderLayout(15, 15));
    getContentPane().setBackground(Color.white);

    // add the logo to the top left
    JPanel logoPnl = new JPanel();
    logoPnl.setBackground(Color.white);
    logoPnl.setLayout(new BoxLayout(logoPnl, BoxLayout.Y_AXIS));
    logoPnl.add(new JLabel(JuxtaUserInterfaceStyle.JUXTA_LOGO));
    logoPnl.add(Box.createVerticalGlue());
    getContentPane().add(logoPnl, BorderLayout.WEST);

    createSetupPane();
    createStatusPane();
    getContentPane().add(this.setupPanel, BorderLayout.CENTER);
    getContentPane().add(createButtonBar(), BorderLayout.SOUTH);

    // create a single scheduled executor to periodically
    // check for export status. There can only be one at any
    // give time, so a pool seemed unnecessary
    this.scheduler = Executors.newSingleThreadScheduledExecutor();

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}

From source file:com.squid.kraken.v4.api.core.customer.AuthServiceImpl.java

public void initGC() {
    modelGC = Executors.newSingleThreadScheduledExecutor();
    ModelGC<AccessToken, AccessTokenPK> gc = new ModelGC<AccessToken, AccessTokenPK>(0, this,
            AccessToken.class);
    modelGCThread = modelGC.scheduleWithFixedDelay(gc, 0, 1, TimeUnit.HOURS);
}