Java Code Examples for java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate()

The following examples show how to use java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@VisibleForTesting
SegmentStatsRecorderImpl(@NonNull AutoScaleProcessor reporter, @NonNull StreamSegmentStore store,
                         @NonNull Duration reportingDuration, @NonNull Duration expiryDuration, @NonNull ScheduledExecutorService executor) {
    this.executor = executor;
    this.pendingCacheLoads = Collections.synchronizedSet(new HashSet<>());

    this.cache = CacheBuilder.newBuilder()
            .initialCapacity(INITIAL_CAPACITY)
            .maximumSize(MAX_CACHE_SIZE)
            .expireAfterAccess(expiryDuration.toMillis(), TimeUnit.MILLISECONDS)
            .build();

    this.cacheCleanup = executor.scheduleAtFixedRate(cache::cleanUp, CACHE_CLEANUP_INTERVAL.toMillis(), 2, TimeUnit.MINUTES);
    this.reportingDuration = reportingDuration;
    this.store = store;
    this.reporter = reporter;
}
 
Example 2
Source Project: dal   File: MarkdownManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void init() {
	if(managerRef.get() !=null)
		return;
	
	synchronized (MarkdownManager.class) {
		if(managerRef.get() !=null)
			return;
		
		ArrayList<ErrorDetector> detectors = new ArrayList<ErrorDetector>();
		// We currently only have Timeout case
		detectors.add(new TimeoutDetector());

		detectorsRef.set(detectors);
		ScheduledExecutorService manager = Executors.newSingleThreadScheduledExecutor();
		manager.scheduleAtFixedRate(new CollectExceptionTask(), durations,
				durations, TimeUnit.MICROSECONDS);

		managerRef.set(manager);
	}
}
 
Example 3
Source Project: jmxmon   File: JMXMonitor.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	if (args.length != 1) {
		throw new IllegalArgumentException("Usage: configFile");
	}
	
	try {
		Config.I.init(args[0]);
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new IllegalStateException(e);	// 抛出异常便于外部脚本感知
	}
	
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	executor.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			runTask();
		}
	}, 0, Config.I.getStep(), TimeUnit.SECONDS);
	
}
 
Example 4
@Override
public DynamicAttributes build(Configuration configuration, Environment environment, List<String> scopes)
{
    DBI jdbi = SoaBundle.getFeatures(environment).getNamedRequired(DBI.class, name);

    final JdbiDynamicAttributes dynamicAttributes = new JdbiDynamicAttributes(jdbi, scopes);
    ScheduledExecutorService service = environment.lifecycle().scheduledExecutorService("JdbiDynamicAttributes-%d", true).build();
    Runnable command = new Runnable()
    {
        @Override
        public void run()
        {
            dynamicAttributes.update();
        }
    };
    service.scheduleAtFixedRate(command, refreshPeriodSeconds, refreshPeriodSeconds, TimeUnit.SECONDS);
    return dynamicAttributes;
}
 
Example 5
@Test
public void testNewScheduledThreadPool() throws InterruptedException {
  String reason = "(can be ignored in Tests) NewScheduledThreadPool";
  Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason);
  int threadCount = 4;
  latch = new CountDownLatch(threadCount);
  ScheduledExecutorService exec = IoTDBThreadPoolFactory
      .newScheduledThreadPool(threadCount / 2, POOL_NAME, handler);
  for (int i = 0; i < threadCount; i++) {
    Runnable task = new TestThread(reason);
    ScheduledFuture<?> future = exec.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
    try {
      future.get();
    } catch (ExecutionException e) {
      assertEquals(reason, e.getCause().getMessage());
      count.addAndGet(1);
      latch.countDown();
    }
  }
  try {
    latch.await();
    assertEquals(count.get(), threadCount);
  } catch (InterruptedException E) {
    fail();
  }
}
 
Example 6
Source Project: statsd-jvm-profiler   File: Agent.java    License: MIT License 6 votes vote down vote up
/**
 * Schedule profilers with a SchedulerExecutorService
 *
 * @param profilers Collection of profilers to schedule
 * @param arguments
 */
private static void scheduleProfilers(Collection<Profiler> profilers, Arguments arguments) {
    // We need to convert to an ExitingScheduledExecutorService so the JVM shuts down
    // when the main thread finishes
    ScheduledExecutorService scheduledExecutorService = MoreExecutors.getExitingScheduledExecutorService(
            (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(profilers.size(), new ProfilerThreadFactory()));

    Map<String, ScheduledFuture<?>> runningProfilers = new HashMap<>(profilers.size());
    Map<String, Profiler> activeProfilers = new HashMap<>(profilers.size());
    for (Profiler profiler : profilers) {
        activeProfilers.put(profiler.getClass().getSimpleName(), profiler);
        ProfilerWorkerThread worker = new ProfilerWorkerThread(profiler, errors);
        ScheduledFuture future =  scheduledExecutorService.scheduleAtFixedRate(worker, EXECUTOR_DELAY, profiler.getPeriod(), profiler.getTimeUnit());
        runningProfilers.put(profiler.getClass().getSimpleName(), future);
    }

    if (arguments.httpServerEnabled) {
        ProfilerServer.startServer(runningProfilers, activeProfilers, arguments.httpPort, isRunning, errors);
    }
}
 
Example 7
@Activate
public void activate(ComponentContext componentContext) {

    try {
        DataHolder.getInstance().setModifiedTime(LoggingUpdaterUtil.readModifiedTime());
        LogConfigUpdater logConfigUpdater =
                new LogConfigUpdater(DataHolder.getInstance().getConfigurationAdmin());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        DataHolder.getInstance().setScheduledExecutorService(scheduledExecutorService);
        scheduledExecutorService.scheduleAtFixedRate(logConfigUpdater, 5000L, 5000L, TimeUnit.MILLISECONDS);
    } catch (LoggingUpdaterException e) {
        log.error("Error while Activating LoggingUpdater component", e);
    }
}
 
Example 8
/**
 * 心跳线程,用于每隔一段时间上报一次临时节点时间
 */
protected void startHeartBeatThread() {
	ScheduledExecutorService schedule = new ScheduledThreadPoolExecutor(1,
			new NamingThreadFactory(THREAD_HEARTBEAT_NAME, true));
	schedule.scheduleAtFixedRate(() -> {
		if (active.get() == false) {
			schedule.shutdownNow();
		} else if (where()) {
			report();
		}
	}, 0L, interval, TimeUnit.MILLISECONDS);
}
 
Example 9
@Override
public void start(final Stage stage) throws Exception
{
    // Standalone item, not in Model
    final PVItem item = new PVItem("sim://sine(-10, 10, 0.2)", 0.0);
    item.setColor(Color.BLUE);
    item.start();

    // Plot for just that item
    final ModelBasedPlot plot = new ModelBasedPlot(true);
    plot.addTrace(item);

    AxisConfig axis = new AxisConfig(true, "Values", true, true, false, Color.DARKRED, -10, 10, false, false, false);
    plot.updateAxis(0, axis );

    final BorderPane layout = new BorderPane(plot.getPlot());
    final Scene scene = new Scene(layout, 800, 600);
    stage.setScene(scene);
    stage.show();

    // Instead of full Controller, simple update task
    final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
    final Runnable fake_controller = () ->
    {
        Platform.runLater(() -> plot.redrawTraces());
    };
    timer.scheduleAtFixedRate(fake_controller, 500, 500, TimeUnit.MILLISECONDS);
}
 
Example 10
Source Project: pentaho-kettle   File: Job.java    License: Apache License 2.0 5 votes vote down vote up
protected ExecutorService startHeartbeat( final long intervalInSeconds ) {

    final ScheduledExecutorService heartbeat = Executors.newSingleThreadScheduledExecutor( new ThreadFactory() {

      @Override
      public Thread newThread( Runnable r ) {
        Thread thread = new Thread( r, "Job Heartbeat Thread for: " + getName() );
        thread.setDaemon( true );
        return thread;
      }
    } );

    heartbeat.scheduleAtFixedRate( new Runnable() {
      public void run() {

        if ( Job.this.isFinished() ) {
          log.logBasic( "Shutting down heartbeat signal for " + jobMeta.getName() );
          shutdownHeartbeat( heartbeat );
          return;
        }

        try {

          log.logDebug( "Triggering heartbeat signal for " + jobMeta.getName() + " at every " + intervalInSeconds
              + " seconds" );
          ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobHeartbeat.id, Job.this );

        } catch ( KettleException e ) {
          log.logError( e.getMessage(), e );
        }
      }
    }, intervalInSeconds /* initial delay */, intervalInSeconds /* interval delay */, TimeUnit.SECONDS );

    return heartbeat;
  }
 
Example 11
public static void main(String[] args) {
    ScheduledExecutorService es = Executors.newScheduledThreadPool(10);
    es.scheduleAtFixedRate(new Runnable() {

        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(System.currentTimeMillis() / 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, 0, 2, TimeUnit.SECONDS);
}
 
Example 12
Source Project: beam   File: MetricsPusher.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
  if (!(metricsSink instanceof NoOpMetricsSink)) {
    ScheduledExecutorService scheduler =
        Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder()
                .setDaemon(true)
                .setNameFormat("MetricsPusher-thread")
                .build());
    scheduledFuture = scheduler.scheduleAtFixedRate(this::run, 0, period, TimeUnit.SECONDS);
  }
}
 
Example 13
Source Project: pentaho-kettle   File: Trans.java    License: Apache License 2.0 5 votes vote down vote up
protected ExecutorService startHeartbeat( final long intervalInSeconds ) {

    ScheduledExecutorService heartbeat = Executors.newSingleThreadScheduledExecutor( new ThreadFactory() {

      @Override
      public Thread newThread( Runnable r ) {
        Thread thread = new Thread( r, "Transformation Heartbeat Thread for: " + getName() );
        thread.setDaemon( true );
        return thread;
      }
    } );

    heartbeat.scheduleAtFixedRate( new Runnable() {
      @Override
      public void run() {
        try {

          if ( Trans.this.isFinished() ) {
            log.logBasic( "Shutting down heartbeat signal for " + getName() );
            shutdownHeartbeat( Trans.this.heartbeat );
            return;
          }

          log.logDebug( "Triggering heartbeat signal for " + getName() + " at every " + intervalInSeconds
            + " seconds" );
          ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.TransformationHeartbeat.id, Trans.this );

        } catch ( KettleException e ) {
          log.logError( e.getMessage(), e );
        }
      }
    }, intervalInSeconds /* initial delay */, intervalInSeconds /* interval delay */, TimeUnit.SECONDS );

    return heartbeat;
  }
 
Example 14
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 15
private VLCWindowEmbed() {

        runOnVLCThread(() -> {
            try {
                SwingUtilities.invokeAndWait(() -> {
                    frame = new JFrame();
                    frame.setBackground(Color.BLACK);
                    frame.setType(JFrame.Type.UTILITY);
                    frame.setTitle(LabelGrabber.INSTANCE.getLabel("video.theme.label"));
                    
                    canvas = new Canvas();
                    canvas.setBackground(Color.BLACK);
                });
                
                mediaPlayerFactory = new MediaPlayerFactory("--no-video-title-show", "--mouse-hide-timeout=0", "--no-xlib");
                videoSurface = mediaPlayerFactory.newVideoSurface(canvas);
                createMediaPlayer();
                
                SwingUtilities.invokeAndWait(() -> {
                    frame.add(canvas);
                    setFullScreen(frame, false);
                    frame.toBack();
                });
                
                init = true;
                LOGGER.log(Level.INFO, "Video initialised ok");
            } catch (Exception ex) {
                LOGGER.log(Level.INFO, "Couldn't initialise video, almost definitely because VLC (or correct version of VLC) was not found.", ex);
            }
        });
        ScheduledExecutorService exc = Executors.newSingleThreadScheduledExecutor();
        exc.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                if (init) {
                    runOnVLCThread(new Runnable() {
                        @Override
                        public void run() {
                            mediaPlayer.setAdjustVideo(true);
                            int hueVal = (int) (hue * 360);
                            if(hueVal>180) hueVal-=360;
                            hueVal += 180;
                            mediaPlayer.setHue(hueVal);
                        }
                    });
                }
            }
        }, 0, 30, TimeUnit.MILLISECONDS);
    }
 
Example 16
public static void main(String[] args) {
	final Shell shell = new Shell();
	shell.setSize(300, 120);
    shell.open();
    
    //use LightweightSystem to create the bridge between SWT and draw2D
	final LightweightSystem lws = new LightweightSystem(shell);		
	
	//Create Gauge
	final ProgressBarFigure progressBarFigure = new ProgressBarFigure();
	
	//Init gauge
	progressBarFigure.setFillColor(
			XYGraphMediaFactory.getInstance().getColor(0, 255, 0));
			
	progressBarFigure.setRange(-100, 100);
	progressBarFigure.setLoLevel(-50);
	progressBarFigure.setLoloLevel(-80);
	progressBarFigure.setHiLevel(60);
	progressBarFigure.setHihiLevel(80);
	progressBarFigure.setMajorTickMarkStepHint(50);
	progressBarFigure.setHorizontal(true);
	progressBarFigure.setOriginIgnored(true);
	
	lws.setContents(progressBarFigure);		
	
	//Update the gauge in another thread.
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(new Runnable() {
		
		public void run() {
			Display.getDefault().asyncExec(new Runnable() {					
				public void run() {
					progressBarFigure.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 17
Source Project: SlyceMessaging   File: MainActivity.java    License: MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(it.snipsnap.slyce_messaging_example.R.layout.activity_main);

    hasLoadedMore = false;

    slyceMessagingFragment = (SlyceMessagingFragment) getFragmentManager().findFragmentById(R.id.fragment_for_slyce_messaging);
    slyceMessagingFragment.setDefaultAvatarUrl("https://scontent-lga3-1.xx.fbcdn.net/v/t1.0-9/10989174_799389040149643_722795835011402620_n.jpg?oh=bff552835c414974cc446043ac3c70ca&oe=580717A5");
    slyceMessagingFragment.setDefaultDisplayName("Matthew Page");
    slyceMessagingFragment.setDefaultUserId("uhtnaeohnuoenhaeuonthhntouaetnheuontheuo");

    slyceMessagingFragment.setOnSendMessageListener(new UserSendsMessageListener() {
        @Override
        public void onUserSendsTextMessage(String text) {
            Log.d("inf", "******************************** " + text);
        }

        @Override
        public void onUserSendsMediaMessage(Uri imageUri) {
            Log.d("inf", "******************************** " + imageUri);
        }
    });

    slyceMessagingFragment.setLoadMoreMessagesListener(new LoadMoreMessagesListener() {
        @Override
        public List<Message> loadMoreMessages() {
            Log.d("info", "loadMoreMessages()");

            if (!hasLoadedMore) {
                hasLoadedMore = true;
                ArrayList<Message> messages = new ArrayList<>();
                GeneralOptionsMessage generalTextMessage = new GeneralOptionsMessage();
                generalTextMessage.setTitle("Started group");
                generalTextMessage.setFinalText("Accepted");
                generalTextMessage.setOptions(new String[]{"Accept", "Reject"});
                generalTextMessage.setOnOptionSelectedListener(new OnOptionSelectedListener() {
                    @Override
                    public String onOptionSelected(int optionSelected) {
                        if (optionSelected == 0) {
                            return "Accepted";
                        } else {
                            return "Rejected";
                        }
                    }
                });
                messages.add(generalTextMessage);
                for (int i = 0; i < 50; i++)
                    messages.add(getRandomMessage());
                messages.add(generalTextMessage);
                Log.d("info", "loadMoreMessages() returns");
                return messages;
            } else {
                slyceMessagingFragment.setMoreMessagesExist(false);
                return new ArrayList<>();
            }
        }
    });

    slyceMessagingFragment.setMoreMessagesExist(true);


    try {
        Thread.sleep(1000 * 3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            TextMessage textMessage = new TextMessage();
            textMessage.setText("Another message...");
            textMessage.setAvatarUrl("https://lh3.googleusercontent.com/-Y86IN-vEObo/AAAAAAAAAAI/AAAAAAAKyAM/6bec6LqLXXA/s0-c-k-no-ns/photo.jpg");
            textMessage.setDisplayName("Gary Johnson");
            textMessage.setUserId("LP");
            textMessage.setDate(new Date().getTime());
            textMessage.setSource(MessageSource.EXTERNAL_USER);
            slyceMessagingFragment.addNewMessage(textMessage);
        }
    }, 3, 3, TimeUnit.SECONDS);
}
 
Example 18
Source Project: kogito-runtimes   File: MultithreadTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Disabled
public void testConcurrencyWithChronThreads() throws InterruptedException {

    final String drl = "package it.intext.drools.fusion.bug;\n" +
            "\n" +
            "import " + MyFact.class.getCanonicalName() + ";\n " +
            " global java.util.List list; \n" +
            "\n" +
            "declare MyFact\n" +
            "\[email protected]( event )\n" +
            "\[email protected]( 1s )\n" +
            "end\n" +
            "\n" +
            "rule \"Dummy\"\n" +
            "timer( cron: 0/1 * * * * ? )\n" +
            "when\n" +
            "  Number( $count : intValue ) from accumulate( MyFact( ) over window:time(1s); sum(1) )\n" +
            "then\n" +
            "    System.out.println($count+\" myfact(s) seen in the last 1 seconds\");\n" +
            "    list.add( $count ); \n" +
            "end";

    final KieBaseConfiguration kbconfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconfig.setOption(EventProcessingOption.STREAM);

    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);

    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("REALTIME"));
    final KieSession ksession = kbase.newKieSession(conf, null);

    final List list = new ArrayList();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();

    final Runner t = new Runner(ksession);
    t.start();
    try {
        final int FACTS_PER_POLL = 1000;
        final int POLL_INTERVAL = 500;

        final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        try {
            executor.scheduleAtFixedRate(
                    () -> {
                        for (int j = 0; j < FACTS_PER_POLL; j++) {
                            ksession.insert(new MyFact());
                        }
                    },
                    0,
                    POLL_INTERVAL,
                    TimeUnit.MILLISECONDS);

            Thread.sleep(10200);
        } finally {
            executor.shutdownNow();
        }
    } finally {
        ksession.halt();
        ksession.dispose();
    }

    t.join();

    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }

    System.out.println("Final size " + ksession.getObjects().size());

    ksession.dispose();
}
 
Example 19
Source Project: DDMQ   File: ConsumerServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private ConsumerServiceImpl() {
    ScheduledExecutorService scheduler = CarreraExecutors.newSingleThreadScheduledExecutor("PullStatsThread");
    scheduler.scheduleAtFixedRate(this::logStats, STATS_INTERVAL, STATS_INTERVAL, TimeUnit.SECONDS);
    pullScheduler = CarreraExecutors.newScheduledThreadPool(32, "PullRequestTimeoutChecker");
    executor = CarreraExecutors.newFixedThreadPool(32, "doGetConsumeStatsWorker", 100000 );
}
 
Example 20
public void start(ScheduledExecutorService service) {
    service.scheduleAtFixedRate(this, 0, 100, TimeUnit.MILLISECONDS);
    this.running = true;
}