Karem
Karem

Reputation: 18103

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

This is a cronjob script. The cronjob is running every minute.

The cronjob is to update a live-counter field in the database.

I'm having two times and a count limiter:

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

How can I out from the start date, end date and limit given make the system calculate a number to add to the counter this execution?

So when the end date is over, the counter should be as big as the limit entered

Example, right now I got this:

if ( $setting['limit'] > $setting['counter'] )
{
        $rand = rand(5, 300);

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

This simply just gives me a number between 5 and 300 and adds to the counter each refresh/execution of the script.

With this there's a big possibility that the counter does not reach the limit, e.g if the start date and the end date is close to eachother and the random values is below 100 theres no way it will reach the limit 5000.

So how can you make the system calculate a correct ratio number to add to the counter, based on the start and end dates, the limit and the current count?

Upvotes: 0

Views: 84

Answers (1)

John V.
John V.

Reputation: 4670

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

Basic ratios, although this is more a math question than a programming question...

Also, you may need to round the result, if you're not using a MySQL type that supports decimals.

So in your cronjob:

$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();

Upvotes: 1

Related Questions