Monday, March 13, 2017

Ignore seconds when querying created_at

I have a scheduled task that runs every 5 minutes that collects some stats on a server I run.

There is a small delay whilst it waits for the request to come back and so records are always being saved 2 or 3 seconds later. I.e the task runs at 2017-14-03 08:00:00, but the records are saved at 2017-14-03 08:00:03.

I am trying to pull the records out to display on a graph. The graph scales to the time period you want to look at (through hard coded buttons that refresh the graph with new data).

The first graph I am trying to do is one over the last 24 hours. Rather than bring back every 5 minute point for the last 24 hours, I just want one per hour. I have built a function to round down to the nearest hour and then get the last 24 hours based off that - it looks like this:

public function last24Hours()
{
    $times = [];
    $time = Carbon::now()->minute(0)->second(0);
    $i = 1;
    while($i <= 24)
    {
        array_push($times, $time->toDateTimeString());
        $time->subHour();
        $i++;
    }

    return $times;
}

Using the times returned, I am trying to query the model with whereIn() like so:

$stats = ServerTracking::whereIn('created_at', $this->last24Hours())->get();

The query runs, but nothing comes back - as the created_at time is a couple of seconds off from what I am querying.

I've hit a bit of a roadblock and cannot think of a way to get around this? Any ideas?



via James

Advertisement