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

The following are Jave code examples for showing how to use scheduleAtFixedRate() of the java.util.concurrent.ScheduledExecutorService class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: JavaStudy   File: ThreadPool.java   Source Code and License Vote up 7 votes
public static void main(String[] args) {
     start=System.currentTimeMillis();
     ScheduledExecutorService threadPool=Executors.newScheduledThreadPool(2);
     for (int i=1;i<=5;i++){
         int num=i;
         threadPool.scheduleAtFixedRate(new Runnable() {
             @Override
             public void run() {
                 try {
                     Thread.sleep(50);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 end=System.currentTimeMillis();
                 System.err.println(Thread.currentThread().getName() + "执行任务:"+num+" 间隔时间:"+(end-start)/1000+"秒");
             }

         }, 2, 5, TimeUnit.SECONDS);
         System.out.println("**");

     }

}
 
Example 2
Project: GitHub   File: Issue1488.java   Source Code and License Vote up 7 votes
public void test_user() throws Exception {
        ExtClassLoader classLoader = new ExtClassLoader();
        final Class clazz = classLoader.loadClass("Issue1488_Server");

        final int THREAD_NUMBER = 10;
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(THREAD_NUMBER);
        for (int i = 0; i < 10; ++i) {
            System.out.println("start....");
            threadPool.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    Map map = new HashMap();
                    map.put("run_id", "aeca30e");
                    map.put("port", 1002);
                    map.put("processId", 3001);
                    System.out.println(JSON.toJSONString(JSON.parseObject(JSON.toJSONString(map), clazz)));
                }
            }, 1, 1, TimeUnit.SECONDS);
        }

        Thread.sleep(1000 * 1000);

//
//        Object obj = JSON.parseObject(json, clazz);
//        assertEquals("{\"process_id\":301,\"run_id\":\"aeca30e\"}", JSON.toJSONString(obj));
    }
 
Example 3
Project: EasyTransaction   File: DataBaseTransactionLogCleanJob.java   Source Code and License Vote up 6 votes
public void init(){
	String cleanTime = logCleanTime;
	Date nextExeucteTime = calcNextExecuteTime(cleanTime);
	long initialDelay = nextExeucteTime.getTime() - System.currentTimeMillis();
	
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("CleanLogJob",true));
	executor.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			try{
				if(master.hasLeaderShip()){
					Calendar instance = Calendar.getInstance();
					instance.add(Calendar.DATE, -logReservedDays);
					LOG.info("START CLEAN EXPIRED TRANSACTION LOGS.DAYS:" + logReservedDays);
					logWritter.cleanFinishedLogs(applicationName, instance.getTime());
					LOG.info("END CLEAN EXPIRED TRANSACTION LOGS.DAYS");
				}else{
					LOG.info("NOT MASTER,do not execute transaction log clean job");
				}
			}catch(Exception e){
				LOG.error("execute clean job error!",e);
			}
		}
	}, initialDelay, 24l*60*60*1000 , TimeUnit.MILLISECONDS);
}
 
Example 4
Project: cornerstone   File: VICoreIgnite.java   Source Code and License Vote up 6 votes
void runCheckThread(){

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new VIThreadFactory("vi-envIgnite"));
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try{
                    if(waitTimes == 0 || waitTimes >MAXTIMES){

                        if(waitTimes != 0){
                            waitTimes = 0;
                        }
                        EnFactory.getEnApp().register();
                    }
                }
                catch (Throwable e){
                    logger.warn("self registration failed!", e);
                }finally {
                    waitTimes++;
                }

            }
        }, 0, DEFAULTINTERVAL, TimeUnit.SECONDS);
    }
 
Example 5
Project: ares   File: RuntimeManager.java   Source Code and License Vote up 5 votes
/**
 * Registers a periodic task.
 * @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);
  }
}
 
Example 6
Project: Lagerta   File: StatisticsDriver.java   Source Code and License Vote up 5 votes
public void startCollecting() {
    ScheduledExecutorService executor = executorManager.getExecutor();

    executor.scheduleAtFixedRate(this, 0, config.getReportFrequency(), TimeUnit.MILLISECONDS);
    executor.scheduleAtFixedRate(
        localStatisticsUpdater,
        config.getReportFrequency(),
        config.getReportFrequency(),
        TimeUnit.MILLISECONDS
    );
}
 
Example 7
Project: outcomes   File: Executors3.java   Source Code and License Vote up 5 votes
private static void test2() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
    int initialDelay = 0;
    int period = 1;
    executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
}
 
Example 8
Project: Lagerta   File: Statistics.java   Source Code and License Vote up 5 votes
static void deployContinuously(Ignite ignite) {
    long reportFrequency = TestsHelper.getLoadTestsStatisticsReportFrequency();
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    final StatisticsDeploymentHelper helper = new StatisticsDeploymentHelper(ignite);

    executor.scheduleAtFixedRate(new Runnable() {
        @Override public void run() {
            helper.deployStatisticsCollector();
        }
    }, 0, reportFrequency, TimeUnit.MILLISECONDS);
}
 
Example 9
Project: fresco_floodlight   File: LoadMonitor.java   Source Code and License Vote up 5 votes
public ScheduledFuture<?> printMonitoring(ScheduledExecutorService ses)
{
    final LoadMonitor mon = this;
    ScheduledFuture<?> monitorTask =
        ses.scheduleAtFixedRate(
            new Runnable() {
                public void run() {
                    System.out.println(mon.getLoad());
                }
            }, LOADMONITOR_SAMPLING_INTERVAL/2,
            LOADMONITOR_SAMPLING_INTERVAL, TimeUnit.MILLISECONDS);
    return monitorTask;
}
 
Example 10
Project: Re-Collector   File: ChunkReaderTest.java   Source Code and License Vote up 5 votes
@Test
public void readPositionEnd() throws IOException, InterruptedException {
    final Utils.LogFile logFile = new Utils.LogFile(100 * 1024, 400, 100);
    logFile.close();
    final ArrayBlockingQueue<FileChunk> chunkQueue = Queues.newArrayBlockingQueue(1);
    final AsynchronousFileChannel channel = AsynchronousFileChannel.open(logFile.getPath(), StandardOpenOption.READ);
    final CountingAsyncFileChannel spy = new CountingAsyncFileChannel(channel);

    final ChunkReader chunkReader = new ChunkReader(mock(FileInput.class), logFile.getPath(), spy, chunkQueue, 10 * 1024,
            FileInput.InitialReadPosition.END, null);

    final ScheduledExecutorService chunkReaderExecutor = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder()
                    .setDaemon(false)
                    .setNameFormat("file-chunk-reader-%d")
                    .setUncaughtExceptionHandler(this)
                    .build()
    );

    final Thread consumer = new Thread() {
        @Override
        public void run() {
            try {
                final FileChunk chunk = chunkQueue.poll(2, TimeUnit.SECONDS);
                assertNull("Reading from the end of the file must not produce a chunk for a non-changing file.", chunk);
            } catch (InterruptedException ignore) {
            }
        }
    };
    consumer.start();
    chunkReaderExecutor.scheduleAtFixedRate(chunkReader, 0, 250, TimeUnit.MILLISECONDS);
    consumer.join();

    // we can process one chunk at a time, so one read is queued, the second is buffered
    assertEquals("The e should be empty", 1, chunkQueue.remainingCapacity());
}
 
Example 11
Project: iTAP-controller   File: LoadMonitor.java   Source Code and License Vote up 5 votes
public ScheduledFuture<?> printMonitoring(ScheduledExecutorService ses)
{
    final LoadMonitor mon = this;
    ScheduledFuture<?> monitorTask =
        ses.scheduleAtFixedRate(
            new Runnable() {
                public void run() {
                    System.out.println(mon.getLoad());
                }
            }, LOADMONITOR_SAMPLING_INTERVAL/2,
            LOADMONITOR_SAMPLING_INTERVAL, TimeUnit.MILLISECONDS);
    return monitorTask;
}
 
Example 12
Project: lambo   File: SystemClock.java   Source Code and License Vote up 5 votes
private void scheduleClockUpdating() {
	ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
		public Thread newThread(Runnable runnable) {
			Thread thread = new Thread(runnable, "System Clock");
			thread.setDaemon(true);
			return thread;
		}
	});
	scheduler.scheduleAtFixedRate(new Runnable() {
		public void run() {
			now.set(System.currentTimeMillis());
		}
	}, period, period, TimeUnit.MILLISECONDS);
}
 
Example 13
Project: elasticsearch_my   File: MeterMetric.java   Source Code and License Vote up 5 votes
public MeterMetric(ScheduledExecutorService tickThread, TimeUnit rateUnit) {
    this.rateUnit = rateUnit;
    this.future = tickThread.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            tick();
        }
    }, INTERVAL, INTERVAL, TimeUnit.SECONDS);
}
 
Example 14
Project: googles-monorepo-demo   File: AbstractScheduledService.java   Source Code and License Vote up 5 votes
/**
 * Returns a {@link Scheduler} that schedules the task using the {@link
 * ScheduledExecutorService#scheduleAtFixedRate} method.
 *
 * @param initialDelay the time to delay first execution
 * @param period the period between successive executions of the task
 * @param unit the time unit of the initialDelay and period parameters
 */
public static Scheduler newFixedRateSchedule(
    final long initialDelay, final long period, final TimeUnit unit) {
  checkNotNull(unit);
  checkArgument(period > 0, "period must be > 0, found %s", period);
  return new Scheduler() {
    @Override
    public Future<?> schedule(
        AbstractService service, ScheduledExecutorService executor, Runnable task) {
      return executor.scheduleAtFixedRate(task, initialDelay, period, unit);
    }
  };
}
 
Example 15
Project: fresco_floodlight   File: LoadMonitor.java   Source Code and License Vote up 5 votes
public ScheduledFuture<?> startMonitoring(ScheduledExecutorService ses)
{
    ScheduledFuture<?> monitorTask =
        ses.scheduleAtFixedRate(
            this, 0,
            LOADMONITOR_SAMPLING_INTERVAL, TimeUnit.MILLISECONDS);
    return monitorTask;
}
 
Example 16
Project: jsf-core   File: ServerSyncSchedule.java   Source Code and License Vote up 5 votes
private void syncServerSchedule() {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("server"));
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                if (RegistryUtil.isOpenProviderBerkeleyDB) {
                    checkTotalCount();
                    syncToDB();
                }
            } catch (Exception e) {
                logger.error("sync server data error:", e);
            }
        }
    }, 30, interval, TimeUnit.SECONDS);
}
 
Example 17
Project: flink-scaffolding   File: RuntimeManager.java   Source Code and License Vote up 5 votes
/**
 * Registers a periodic task.
 * @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);
  }
}
 
Example 18
Project: MDC-Discord-Bot   File: MuteHandler.java   Source Code and License Vote up 4 votes
public static void init()
{
    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1);
    service.scheduleAtFixedRate(MuteHandler::checkMutedMembers, 60, 15, TimeUnit.SECONDS);
}
 
Example 19
Project: Saber-Bot   File: ScheduleManager.java   Source Code and License Vote up 4 votes
public void initScheduleSync()
{
    // every 15 minutes create a thread to check for schedules to sync
    ScheduledExecutorService syncScheduler = Executors.newScheduledThreadPool(1);
    syncScheduler.scheduleAtFixedRate( new ScheduleSyncer(), 60*15, 60*15, TimeUnit.SECONDS );
}
 
Example 20
Project: tasfe-framework   File: KafkaMonitor.java   Source Code and License Vote up 4 votes
public void intervalTimer() {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    //每5秒进行检查 检测kafka状态是否由false变为true,启动复写机制
    service.scheduleAtFixedRate(kafkaTestProducer(), 0, 10, TimeUnit.SECONDS);
}