List of usage examples for java.util.concurrent ScheduledExecutorService schedule
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
From source file:ScheduledTask.java
public static void main(String[] args) { // Get an executor with 3 threads ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3); ScheduledTask task1 = new ScheduledTask(1); ScheduledTask task2 = new ScheduledTask(2); // Task #1 will run after 2 seconds sexec.schedule(task1, 2, TimeUnit.SECONDS); // Task #2 runs after 5 seconds delay and keep running every 10 seconds sexec.scheduleAtFixedRate(task2, 5, 10, TimeUnit.SECONDS); try {/*from w w w.ja v a2s.c om*/ TimeUnit.SECONDS.sleep(60); } catch (InterruptedException e) { e.printStackTrace(); } sexec.shutdown(); }
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 www .j av a 2 s . co m 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: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);//w w w . j a v a 2 s .c o 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.sourcepit.consul.forwarder.Main.java
public static void main(String[] args) { final String dockerUri = "http://192.168.56.101:2375"; final String consulUri = "http://192.168.56.101:8500"; final int fetchConsulStateInterval = 30; final int fetchDockerStateInterval = 30; final int dispatchItemsInterval = 2; final int requestDockerStateDelay = 5; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(10); final HttpClient httpClient = HttpClients.createMinimal(connManager); final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>(); final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) { @Override/* w w w . j a va 2s.co m*/ protected void doHandle(JsonObject consulState) { final JsonObject item = createItem("ConsulState", consulState); LOG.debug(item.toString()); queue.add(item); } }; final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) { @Override protected void doHandle(JsonArray dockerState) { final JsonObject item = createItem("DockerState", dockerState); LOG.debug(item.toString()); queue.add(item); } }; final ConsulForwarderState forwarderState = new ConsulForwarderState(); final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) { @Override protected void handleDockerState(JsonArray dockerState) { forwarderState.applyDockerState(dockerState); } @Override protected void handleDockerEvents(JsonArray dockerEvents) { // trigger docker state update scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS); } @Override protected void handleConsulState(JsonObject consulState) { forwarderState.applyConsulState(consulState); } }, 0, dispatchItemsInterval, TimeUnit.SECONDS); final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) { @Override protected void handle(JsonObject event) { queue.add(createItem("DockerEvent", event)); } }; final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") { @Override public void interrupt() { eventObserver.die(); super.interrupt(); } }; eventObserverThread.start(); }
From source file:edu.umass.cs.nio.MessageNIOTransport.java
@SuppressWarnings("unchecked") public static void main(String[] args) { int msgNum = 0; int port = 2000; int nNodes = 100; SampleNodeConfig<Integer> snc = new SampleNodeConfig<Integer>(port); snc.localSetup(nNodes + 2);/*from w w w. ja v a 2s.co m*/ MessageExtractor[] workers = new MessageExtractor[nNodes + 1]; for (int i = 0; i < nNodes + 1; i++) { workers[i] = new MessageExtractor(new PacketDemultiplexerDefault()); } MessageNIOTransport<?, ?>[] niots = new MessageNIOTransport[nNodes]; try { int smallNNodes = 2; for (int i = 0; i < smallNNodes; i++) { niots[i] = new MessageNIOTransport<Integer, JSONObject>(i, snc, workers[i]); new Thread(niots[i]).start(); } /* Test a few simple hellos. The sleep is there to test that the * successive writes do not "accidentally" benefit from concurrency, * i.e., to check that OP_WRITE flags will be set correctly. */ ((MessageNIOTransport<Integer, JSONObject>) niots[1]).sendToIDInternal(0, JSONify(msgNum++, "Hello from 1 to 0")); ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1, JSONify(msgNum++, "Hello back from 0 to 1")); ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1, JSONify(msgNum++, "Second hello back from 0 to 1")); try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1, JSONify(msgNum++, "Third hello back from 0 to 1")); ((MessageNIOTransport<Integer, JSONObject>) niots[1]).sendToIDInternal(0, JSONify(msgNum++, "Thank you for all the hellos back from 1 to 0")); // ////////////////////////////////////////////////////////////////////// int seqTestNum = 1; Thread.sleep(2000); System.out.println("\n\n\nBeginning test of " + seqTestNum + " random, sequential messages"); Thread.sleep(1000); // ////////////////////////////////////////////////////////////////////// // Create the remaining nodes up to nNodes for (int i = smallNNodes; i < nNodes; i++) { niots[i] = new MessageNIOTransport<Integer, JSONObject>(i, snc, workers[i]); new Thread(niots[i]).start(); } // Test a random, sequential communication pattern for (int i = 0; i < nNodes * seqTestNum; i++) { int k = (int) (Math.random() * nNodes); int j = (int) (Math.random() * nNodes); System.out.println("Message " + i + " with msgNum " + msgNum); ((MessageNIOTransport<Integer, JSONObject>) niots[k]).sendToIDInternal(j, JSONify(msgNum++, "Hello from " + k + " to " + j)); } int oneToOneTestNum = 1; // ////////////////////////////////////////////////////////////////////// Thread.sleep(1000); System.out.println("\n\n\nBeginning test of " + oneToOneTestNum * nNodes + " random, concurrent, 1-to-1 messages with emulated delays"); Thread.sleep(1000); // ////////////////////////////////////////////////////////////////////// // Random, concurrent communication pattern with emulated delays ScheduledExecutorService execpool = Executors.newScheduledThreadPool(5); class TX extends TimerTask { MessageNIOTransport<Integer, JSONObject> sndr = null; private int rcvr = -1; int msgNum = -1; TX(int i, int id, MessageNIOTransport<?, ?>[] n, int m) { sndr = (MessageNIOTransport<Integer, JSONObject>) n[i]; rcvr = id; msgNum = m; } TX(MessageNIOTransport<Integer, JSONObject> niot, int id, int m) { sndr = niot; rcvr = id; msgNum = m; } public void run() { try { sndr.sendToIDInternal(rcvr, JSONify(msgNum, "Hello from " + sndr.myID + " to " + rcvr)); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } JSONDelayEmulator.emulateDelays(); MessageNIOTransport<Integer, JSONObject> concurrentSender = new MessageNIOTransport<Integer, JSONObject>( nNodes, snc, workers[nNodes]); new Thread(concurrentSender).start(); ScheduledFuture<?>[] futuresRandom = new ScheduledFuture[nNodes * oneToOneTestNum]; for (int i = 0; i < nNodes * oneToOneTestNum; i++) { TX task = new TX(concurrentSender, 0, msgNum++); System.out.println("Scheduling random message " + i + " with msgNum " + msgNum); futuresRandom[i] = execpool.schedule(task, 0, TimeUnit.MILLISECONDS); } for (int i = 0; i < nNodes * oneToOneTestNum; i++) { try { futuresRandom[i].get(); } catch (Exception e) { e.printStackTrace(); } } // ////////////////////////////////////////////////////////////////////// Thread.sleep(1000); System.out.println( "\n\n\nBeginning test of random, concurrent, " + " any-to-any messages with emulated delays"); Thread.sleep(1000); // ////////////////////////////////////////////////////////////////////// int load = nNodes * 25; int msgsToFailed = 0; ScheduledFuture<?>[] futures = new ScheduledFuture[load]; for (int i = 0; i < load; i++) { int k = (int) (Math.random() * nNodes); int j = (int) (Math.random() * nNodes); // long millis = (long)(Math.random()*1000); if (i % 100 == 0) { // Periodically try sending to a non-existent node j = nNodes + 1; msgsToFailed++; } TX task = new TX(k, j, niots, msgNum++); System.out.println("Scheduling random message " + i + " with msgNum " + msgNum); futures[i] = (ScheduledFuture<?>) execpool.schedule(task, 0, TimeUnit.MILLISECONDS); } int numExceptions = 0; for (int i = 0; i < load; i++) { try { futures[i].get(); } catch (Exception e) { // e.printStackTrace(); numExceptions++; } } // //////////////////////////////////////////////////////////////// Thread.sleep(2000); System.out.println("\n\n\nPrinting overall stats. Number of exceptions = " + numExceptions); System.out.println((new NIOInstrumenter() + "\n")); boolean pending = false; for (int i = 0; i < nNodes; i++) { if (niots[i].getPendingSize() > 0) { System.out.println("Pending messages at node " + i + " : " + niots[i].getPendingSize()); pending = true; } } int missing = NIOInstrumenter.getMissing(); assert (pending == false || missing == msgsToFailed) : "Unsent pending messages in NIO"; for (NIOTransport<?> niot : niots) { niot.stop(); } concurrentSender.stop(); execpool.shutdown(); if (!pending || missing == msgsToFailed) { System.out.println("\nSUCCESS: no pending messages to non-failed nodes!"); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
/*** * // w w w . j av a 2 s . co m * @param runnable * @param delayTime * @param size */ public static void newScheduedThreadPool(Runnable runnable, long delayTime, int size) { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(size); scheduledThreadPool.schedule(runnable, delayTime, TimeUnit.SECONDS); }
From source file:com.appnexus.opensdk.PBImplementation.java
private static void captureImage(final Context context, final View view, final String auctionInfo) { //Handler was blocking UI thread. ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.schedule(new Runnable() { @Override/* ww w .java 2s . co m*/ public void run() { byte[] imageBytes = BitmapToByte(captureView(view)); Clog.d(Clog.baseLogTag, "PITBULL image size: " + imageBytes.length + " bytes"); sendBroadcast(context, auctionInfo, imageBytes); } }, PB_CAPTURE_DELAY_MS, TimeUnit.MILLISECONDS); }
From source file:com.acmutv.ontoqa.tool.runtime.RuntimeManager.java
/** * Registers a periodic task.//from w ww . jav a2 s.c o m * @param task the task to execute. * @param delay the delay to first execution. * @param period the period between executions. * @param timeout the time to interruption. * @param unit the time unit. */ private static void registerPeriodic(Runnable task, long delay, long period, long timeout, TimeUnit unit) { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> handler = scheduler.scheduleAtFixedRate(task, delay, period, unit); if (timeout > 0) { Runnable interrupt = () -> handler.cancel(true); scheduler.schedule(interrupt, timeout, TimeUnit.SECONDS); } }
From source file:org.graylog2.Main.java
private static void initializeMessageRetentionThread(ScheduledExecutorService scheduler) { // Schedule first run. This is NOT at fixed rate. Thread will itself schedule next run with current frequency setting from database. scheduler.schedule(new MessageRetentionThread(), 0, TimeUnit.SECONDS); LOG.info("Retention time management active."); }
From source file:com.rks.musicx.misc.utils.Sleeptimer.java
private static void startTimer(View v, final int minutes, Context c) { final String impossible = c.getString(R.string.impossible); final String minute = c.getString(R.string.minute); final String minutess = c.getString(R.string.minutes); final String stop = c.getString(R.string.stop); final String minuteTxt; final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final int delay = (minutes * 60) * 1000; if (delay == 0) { Toast.makeText(c, impossible, Toast.LENGTH_LONG).show(); return;/* w w w . j a v a 2 s . co m*/ } if (minutes < 10) { minuteTxt = minute; } else { minuteTxt = minutess; } mTask = scheduler.schedule(new runner(c), delay, TimeUnit.MILLISECONDS); Toast.makeText(c, stop + " " + minutes + " " + minuteTxt, Toast.LENGTH_LONG).show(); running = true; setState(true); reduceVolume(delay); }