首页 > 代码库 > [django1.6]跑批任务错误(2006, 'MySQL server has gone away')
[django1.6]跑批任务错误(2006, 'MySQL server has gone away')
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
作者orangleliu 采用署名-非商业性使用-相同方式共享协议
[django1.6]跑批任务错误(2006, 'MySQL server has gone away')