[django1.6]跑批任务错误(2006, 'MySQL server has gone away')

有个django的定时任务的需求,调用django的orm来对数据库进行数据处理。 


在交互环境下直接启动pyhton脚本没有问题,放在定时任务中时候,总是出现
(2006, 'MySQL server has gone away') 的错误,开始以为是定时框架外部调用的问题,但是后来想想也不合理,为啥直接在shell中调用就没错呢,
想到django1.6的一些数据库连接的新属性(例如持久化连接等)会不会有影响,于是google了下。


看到django官网上有人提过这个类似于bug的东西: 有兴趣可以浏览一遍
https://code.djangoproject.com/ticket/21597

如果单纯的查询这个数据库错误,很多都是让你修改mysql的配置,看下这里最终给的建议把。
If you hit this problem and don't want to understand what's going on, don't reopen this ticket, just do this:

RECOMMENDED SOLUTION: close the connection with from django.db import connection; connection.close() when you know that your program is going to be idle for a long time.
CRAPPY SOLUTION: increase wait_timeout so it's longer than the maximum idle time of your program.
In this context, idle time is the time between two successive database queries.

这个方案就说把django到mysql的数据库连接关闭了,然后重新建立一个来查询,如果想了解下为什么,可以重头看下这讨论。

from django.db import connection

def is_connection_usable():
try:
connection.connection.ping()
except:
return False
else:
return True

def do_work():
while(True): # Endless loop that keeps the worker going (simplified)
if not is_connection_usable():
connection.close()
try:
do_a_bit_of_work()
except:
logger.exception("Something bad happened, trying again")
sleep(1)


简单的理解,就是django1.6 会自动保持连接, 因为我这个任务时24小时执行一次, 第一执行的时候django和mysql建立的一个链接A, 结果这个任务10分钟就完成了,连接A开始睡眠,django继续保持这连接。 

23小时50分钟以后,这个任务又开始执行了,但是由于msyql的waittime默认是8个小时,连接A这个时候已经死了(msyql单方面解除合同,django还蒙在鼓里),django还用连接A去连接mysql,肯定得到一个gone away的结果。

所有我们在每次执行任务之前去检查连接是否存活,如果没了那么就close,django自动重新建立一个,这样就消除了上面的错误。

本文出自 “orangleliu笔记本” 博客,转载请务必保留此出处http://blog.csdn.net/orangleliu/article/details/41480417

原文地址:https://www.cnblogs.com/ExMan/p/9888077.html