AKAI TSUKI

System development or Technical something

処理開始時間を制御する

その1

public class Controller
{
    private long delayedTime_ = 0;
    
    public void process(DelayedEvent event)
    {
        long nowTime = System.currentTimeMillis();
        
        long eventTime = event.getEventTime();
        
        long differenceTime = nowTime - eventTime;
        
        long checkTime = delayedTime_ - differenceTime;
        
        if( checkTime > 0)
        {
            try
            {
                Thread.sleep(checkTime);
            }
            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

その2

public class SpeedController
{
    private int counter_ = 0;

    private int maxCountValue_ = 10;

    private long firstTimeValue_ = 0;

    private long interval_ = 1000;

    public synchronized void process()
    {
        this.counter_++;

        if (this.counter_ == 1)
        {
            // 最初にカウントした時刻を保存する。
            this.firstTimeValue_ = System.currentTimeMillis();
        }
        else if (this.counter_ == this.maxCountValue_)
        {
            // 最大カウント数に達したら
            long nowTime = System.currentTimeMillis();

            // 最初にカウントした時間からの差分
            long differenceTime = nowTime - this.firstTimeValue_;

            // インターバルと比較して、残りのウエイトタイムを算出する
            long waitTime = this.interval_ - differenceTime;

            if (waitTime > 0)
            {
                try
                {
                    Thread.sleep(waitTime);
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            this.counter_ = 0;

        }

    }

    /**
     * @param maxCountValue the maxCountValue to set
     */
    public void setMaxCountValue(int maxCountValue)
    {
        maxCountValue_ = maxCountValue;
    }

    /**
     * @param interval the interval to set
     */
    public void setInterval(long interval)
    {
        interval_ = interval;
    }

}