让系统根据php中的日期计算要添加到计数器的数量


Letting the system calculate how much to add to counter based on dates in php

这是一个cronjob脚本。cronjob每分钟都在运行。

cronjob用于更新数据库中的活动计数器字段。

我有两次和一个计数限制器:

start: 2012-08-29 09:55:00
end: 2012-08-29 19:00:00
limit: 5000

我如何才能从开始日期、结束日期和给定的限制中出来,使系统计算出一个数字来添加到计数器中执行?

因此,当结束日期结束时,计数器应该与输入的限额一样大

例如,现在我得到了这个:

if ( $setting['limit'] > $setting['counter'] )
{
        $rand = rand(5, 300);
        DB::update('settings')
        ->set(array('counter' => DB::expr('counter+ '.$rand)))
        ->where('id', '=', $setting['id'])
            ->execute();
}   

这只是给我一个介于5和300之间的数字,并在每次刷新/执行脚本时将其添加到计数器中。

这样,计数器很有可能没有达到极限,例如,如果开始日期和结束日期彼此接近,并且随机值低于100,则不可能达到极限5000。

那么,你如何让系统根据开始和结束日期、限制和当前计数计算出一个正确的比率数字添加到计数器中呢?

Counter Limit * (Current time in minutes - Start time in minutes)/(End time in minutes - Start time in minutes) = Current counter number

基本比率,尽管这更多的是一个数学问题而不是一个编程问题。。。

此外,如果您没有使用支持小数的MySQL类型,则可能需要对结果进行四舍五入。

所以在你的裙带上:

$start=strtotime($setting["starttime"]);//Or whatever your local copy of the start time is
$end=strtotime($setting["endtime"]);//Or whatever your local copy of the end time is
$current=time();
$counter = $current>=$end?$setting["limit"]:round($setting['limit'] * ($current-$start)/($end-$start));
DB::update('settings')
    ->set(array('counter' => $counter))
    ->where('id', '=', $setting['id'])
        ->execute();