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:Main.java

public static void main(String[] args) {
    for (int i = 0; i < 200; i++)
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Main(), 1, 10, TimeUnit.SECONDS);
}

From source file:Main.java

public static void main(String[] args) {
    // Get the scheduler
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    // Get a handle, starting now, with a 10 second delay
    final ScheduledFuture<?> timeHandle = scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10,
            SECONDS);/* www.  j  av a2  s.co m*/

    // Schedule the event, and run for 1 hour (60 * 60 seconds)
    scheduler.schedule(new Runnable() {
        public void run() {
            timeHandle.cancel(false);
        }
    }, 60 * 60, SECONDS);

    /**
     * On some platforms, you'll have to setup this infinite loop to see output
    while (true) { }
     */
}

From source file:org.openscada.hds.test.HDSApplication5.java

public static void main(final String[] args) throws Exception {
    final File base = new File("base", "data1");

    FileUtils.deleteDirectory(base.getParentFile());
    base.mkdirs();/*from   w  ww.  j  ava  2 s. c om*/

    final DataFilePool pool = new DataFilePool(10000);

    final File file1 = new File(base, "f1");

    {
        final DataFileAccessorImpl accessor = DataFileAccessorImpl.create(file1, new Date(), new Date());
        accessor.dispose();
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 1");
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 2");
    }

    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);

        try {
            System.out.println("Try 3 - 1");

            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Dispose 1");
                    accessor1.dispose();
                    System.out.println("Disposed 1");
                }
            }, 3000, TimeUnit.MILLISECONDS);

            final DataFileAccessor accessor2 = pool.getAccessor(file1);

            if (accessor2 != null) {
                System.out.println("Finally received");
                accessor2.dispose();
            }
        } finally {
            accessor1.dispose();
        }
        System.out.println("Try 3 - 2");

        accessor1.dispose();
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 4");
    }

    pool.dispose();

    executorService.shutdown();
}

From source file:example.ReceiveNumbers.java

/**
 * @param args/*from w w  w  . j a v a 2 s  .  c om*/
 * @throws MalformedURLException
 * @throws JSONException
 */
public static void main(String[] args) throws MalformedURLException, JSONException {
    // TODO Auto-generated method stub

    JSONObject previousSub = new JSONObject(
            "{'id':'test-java-666','desc':'test-java-666', 'subkey':'GPS-71454020-queu'}");

    MyAEONCallbacks myCallBack = new MyAEONCallbacks();
    final AEONSDK sdk = new AEONSDK(Config.SUB_URL, Config.YOUR_ID, Config.YOUR_DESC);
    //final AEONSDK sdk = new AEONSDK(Config.SUB_URL, previousSub);
    JSONObject subscription = sdk.subscribe(myCallBack);

    if (subscription == null) {
        System.out.println("Something went wrong I dont have a subscription");
        return;
    }
    System.out.println("subscription received " + subscription.toString());

    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*   
          sdk.deleteSubscription();
                  
          System.out.println("Deleted subscription: if some one is publish in the channel you will lost it for ever.");
                  
          try {
             TimeUnit.SECONDS.sleep(3);
          } catch (InterruptedException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
                  
          System.out.println("Ok, lets have another new subscription.");
                  
          subscription = sdk.subscribe(myCallBack);      */

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        boolean paused = false;

        @Override
        public void run() {

            System.out.println("Ok lets make a little break of 5 seconds. After that the subscription"
                    + " will continue. And messages published while our break will be delivered inmediatly");
            if (!paused) {
                sdk.pauseSusbscription();
                paused = true;
            } else {
                sdk.continueSubscription();
                paused = false;
            }

        }
    }, 1, 5, TimeUnit.SECONDS);

}

From source file:org.dcm4che3.tool.ianscp.IanSCP.java

public static void main(String[] args) {
    try {/*from  w ww  .j av  a2 s . c om*/
        CommandLine cl = parseComandLine(args);
        Device device = new Device("ianscp");
        ApplicationEntity ae = new ApplicationEntity("*");
        device.addApplicationEntity(ae);
        Connection conn = new Connection();
        device.addConnection(conn);
        ae.addConnection(conn);
        IanSCPTool main = new IanSCPTool(device, ae);
        CLIUtils.configureBindServer(conn, ae, cl);
        CLIUtils.configure(conn, cl);
        configureTransferCapability(ae, cl);
        main.setResponseStatus(CLIUtils.getIntOption(cl, "status", 0));
        main.setStorageDirectory(getStorageDirectory(cl));
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        device.setScheduledExecutor(scheduledExecutorService);
        device.setExecutor(executorService);
        device.bindConnections();
    } catch (ParseException e) {
        System.err.println("ianscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("ianscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.dcm4che3.tool.syslogd.Syslogd.java

public static void main(String[] args) {
    try {//from w w  w.jav  a2s.c o  m
        CommandLine cl = parseComandLine(args);
        Syslogd main = new Syslogd();
        configure(main, cl);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setScheduledExecutor(scheduledExecutorService);
        main.device.setExecutor(executorService);
        main.device.bindConnections();
    } catch (ParseException e) {
        System.err.println("syslogd: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("syslogd: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.dcm4che.tool.ianscp.IanSCP.java

public static void main(String[] args) {
    try {//w  ww  .  jav  a  2s .  co m
        CommandLine cl = parseComandLine(args);
        IanSCP main = new IanSCP();
        CLIUtils.configureBindServer(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        configureTransferCapability(main.ae, cl);
        main.setStatus(CLIUtils.getIntOption(cl, "status", 0));
        main.setStorageDirectory(getStorageDirectory(cl));
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.setScheduledExecutor(scheduledExecutorService);
        main.setExecutor(executorService);
        main.bindConnections();
    } catch (ParseException e) {
        System.err.println("ianscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("ianscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.dcm4che.tool.mppsscp.MppsSCP.java

public static void main(String[] args) {
    try {//  w  w  w.j a  v  a 2  s .co m
        CommandLine cl = parseComandLine(args);
        MppsSCP main = new MppsSCP();
        CLIUtils.configureBindServer(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        configureTransferCapability(main.ae, cl);
        configureStorageDirectory(main, cl);
        configureIODs(main, cl);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setScheduledExecutor(scheduledExecutorService);
        main.device.setExecutor(executorService);
        main.device.bindConnections();
    } catch (ParseException e) {
        System.err.println("mppsscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("mppsscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:gobblin.restli.throttling.LocalStressTest.java

public static void main(String[] args) throws Exception {

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();//from ww w  . j  ava 2  s  .  c  o m
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:org.dcm4che.tool.ianscu.IanSCU.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from  w  ww.ja  v  a  2  s  . c o m
        CommandLine cl = parseComandLine(args);
        final IanSCU main = new IanSCU();
        configureIAN(main, cl);
        CLIUtils.configureConnect(main.remote, main.rq, cl);
        CLIUtils.configureBind(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        main.remote.setTlsProtocols(main.conn.getTlsProtocols());
        main.remote.setTlsCipherSuites(main.conn.getTlsCipherSuites());
        main.setTransferSyntaxes(CLIUtils.transferSyntaxesOf(cl));
        CLIUtils.addAttributes(main.attrs, cl.getOptionValues("s"));
        main.setUIDSuffix(cl.getOptionValue("uid-suffix"));
        List<String> argList = cl.getArgList();
        boolean echo = argList.isEmpty();
        if (!echo) {
            System.out.println(rb.getString("scanning"));
            DicomFiles.scan(argList, new DicomFiles.Callback() {

                @Override
                public boolean dicomFile(File f, Attributes fmi, long dsPos, Attributes ds) {
                    if (UID.InstanceAvailabilityNotificationSOPClass
                            .equals(fmi.getString(Tag.MediaStorageSOPClassUID))) {
                        return main.addIAN(fmi.getString(Tag.MediaStorageSOPInstanceUID), ds);
                    }
                    return main.addInstance(ds);
                }
            });
        }
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setExecutor(executorService);
        main.device.setScheduledExecutor(scheduledExecutorService);
        try {
            main.open();
            if (echo)
                main.echo();
            else
                main.sendIans();
        } finally {
            main.close();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
        }
    } catch (ParseException e) {
        System.err.println("ianscu: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("ianscu: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}