Search code examples
javarate

Execute java code X times within 3600 ticks


I have a Clock class running as a thread. Multiple producer threads should produce objects based on the ticks of said clock. The producers can be configured with a constructor parameter (double), e.g. productionRate = 550 (meaning 550 objects every 3600 ticks (each tick representing a second so one hour).

In the code below you can see the conversion of the hourly rate to a number representing how many ticks are to pass between ticks. If using my example number, that would be execution every 6,54 ticks. Now I can't find a way to define the if conditions to really produce according to the rate, which should be obvious when looking at the code. Currently, most of the time no vehicle is created because it is way to imprecise.

int curTicks = this.clock.getTicks();
double realFeedRate = 1 / (this.vehicleFeedRate / 3600);

if ((curTicks % (int) Math.round(realFeedRate) == 0 || curTicks - lastExecutionTicks == 0))
{
    //Produce...
}

Now, is there a cleaner way to accomplish a consistent production rate and have 550 (+- only a few) objects created after 3600 ticks (one simulated hour)? Unfortunately, I am required to use my own implementation of a Clock class and cannot use any Timers provided by Java.


Solution

  • You can save/calculate the time when the next action should occur instead of checking the exact tick number, which you might not hit. At some point you will pass this stored time/value and then you know you have to do your action (like adding your object). The pseudo code will look like this:

    long nextActionAfterTick;
    nextActionAfterTick = /* calculate the next tick */;
    
    while(/* your loop */)
    {
        if (nextActionAfterTick < this.clock.getTicks()) {
        {
            doYourAction();
            nextActionAfterTick = /* calculate the next tick */;
        }
    }