private static void executeAtTargetRate()

in java/KinesisTestProducers/src/main/java/com/amazonaws/kinesis/producer/SampleKPLProducer.java [64:98]


    private static void executeAtTargetRate(final ScheduledExecutorService exec, final Runnable task, final AtomicLong counter, 
                                            final int durationSeconds, final int ratePerSecond)
    {
        exec.scheduleWithFixedDelay(new Runnable()
        {
            final long startTime = System.nanoTime();

            @Override
            public void run()
            {
                double secondsRun = (System.nanoTime() - startTime) / 1e9;
                double targetCount = Math.min(durationSeconds, secondsRun) * ratePerSecond;

                while (counter.get() < targetCount)
                {
                    counter.getAndIncrement();
                    try
                    {
                        task.run();
                    }
                    catch (Exception e)
                    {
                        System.err.println("Error running task: " + e.getMessage());
                        e.printStackTrace();
                        System.exit(1);
                    }
                }

                if (secondsRun >= durationSeconds)
                {
                    exec.shutdown();
                }
            }
        }, 0, 1, TimeUnit.MILLISECONDS);
    }