如何告诉PHP仅在一段时间内等待SQL查询?

I have a mysqli_query() in a PHP script which usually takes about 10 ms to finish. However, sometimes it takes about 5000 ms. This query isn't important for the site to function properly, i.e. it can be ignored if it takes for more than 10 ms.

Is this possible to do?

Something like:

<?php

// microtime here is X
$query = mysqli_query($connection, "(do something)");
// if difference between time now and previous time is bigger than 10 ms,
// skip waiting for the $query result and go on

?>

If anything like this is possible, can we also cancel the running query, so that MySQL server knows we don't want the result anymore and stops processing it?

Since the query is not sensitive, you should cache the results instead of hitting the database each time.

PHP provides mysqlnd-qc the (qc is for query cache) which works with APC and friends to cache the results of MySQL queries.

The other option is to cache the template instead. Smarty has this included. This means you render the page once, and then only render it after a certain fixed time.