Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a php script from timing out because of a long mysql query

Tags:

php

mysql

timeout

I have an update query being run by a cron task that's timing out. The query takes, on average, five minutes to execute when executed in navicat.

The code looks roughly like this. It's quite simple:

// $db is a mysqli link
set_time_limit (0); // should keep the script from timing out
$query = "SLOW QUERY";
$result = $db->query($query);
if (!$result)
    echo "error";

Even though the script shouldn't timeout, the time spent waiting on the sql call still seems to be subject to a timeout.

Is there an asynchronous call that can be used? Or adjust the timeout?

Is the timeout different because it's being called from the command line rather than through Apache?

Thanks

like image 203
Eric Goodwin Avatar asked Dec 13 '08 17:12

Eric Goodwin


People also ask

How can increase query execution time limit in MySQL?

SET GLOBAL MAX_EXECUTION_TIME=1000; Then any SELECT statement run against this MySQL instance will be aborted if it takes more than 1 second to complete. The default for the GLOBAL variable is 0, which means that there is no global time limit.

How do I set query timeout in MySQL?

Can I adjust the timeout? Yes, go to Preferences, SQL Editor, and adjust the DBMS connection read time out option that defaults to 600 seconds. This sets the maximum amount of time (in seconds) that a query can take before MySQL Workbench disconnects from the MySQL server.

What is Max_execution_time in MySQL?

The MAX_EXECUTION_TIME( N ) hint sets a statement execution timeout of N milliseconds. If this option is absent or N is 0, the statement timeout established by the max_execution_time system variable applies.


2 Answers

According to the manual:

Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running.

So it's unlikely to have anything to do with PHP's time limit. What message are you getting when it times out? Perhaps there's a MySQL setting involved.

like image 20
JW. Avatar answered Oct 04 '22 20:10

JW.


I had the same problem somwhere, and "solved" it with the following code (first two lines of my file):

set_time_limit(0);
ignore_user_abort(1);
like image 62
Karsten Avatar answered Oct 04 '22 19:10

Karsten