【问题标题】:Codeigniter Cron job which consume more time then insert to databaseCodeigniter Cron 作业消耗更多时间然后插入数据库
【发布时间】:2017-01-05 17:57:53
【问题描述】:

我有一个cron job,它调用以下codeigniter controller
但这耗时
其中计算和操作更多的操作(平均需要 5 分钟)
然后在数据库中插入值

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mycron extends CI_Controller {

    public function cron_function()
    {
        // simulate time cost operations
        sleep(300); // 5 mint = 5 *60 = 300 sec

        $this->load->database();    // line1
        $this->db->reconnect();     // line2

        $this           -> db -> set    ( 'source_id',  '11');
        $this           -> db -> set    ( 'title',  'TTL');
        $query = $this  -> db -> insert ( 'my_table' );

        echo 'END ...'; 
    }
}

我的问题
没有两条线 line1/line2
当数据库在操作消耗时间后尝试连接时,结果将是

SQL Error: 2006: MySQL server has gone away

然后当尝试使用 2 行将修复 RE_CONNECT 应用于数据库时
我们面对

A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by 
(output started at .../system/database/drivers/mysqli/mysqli_driver.php:392)
Filename: core/Common.php
Line Number: 568
Backtrace:

A PHP Error was encountered
Severity: Error
Message: Call to a member function real_escape_string() on boolean
Filename: mysqli/mysqli_driver.php
Line Number: 392
Backtrace:

【问题讨论】:

  • 检查你的`my.cnf'中的wait_timeout变量

标签: php codeigniter cron


【解决方案1】:

我建议在 cron 控制器中创建第二个方法,只负责将数据插入数据库。

然后,在耗时的操作完成后,您可以将生成的数据以curl 发布到第二种方法,从而绕过 MySQL 超时限制。

【讨论】:

    【解决方案2】:

    我禁用了 database 库的自动加载
    旧代码

    $autoload['libraries'] = array('database');
    

    成为

    $autoload['libraries'] = array();
    

    并在调用DB语句之前手动加载

    $this->load->database();
    

    所以数据库连接会在代价高昂的操作结束后打开

    那么这个时间(代价高昂的操作)将不会被视为数据库同步操作时间
    与自动加载 database 库相反,它在页面加载时启动计时器

    【讨论】:

    • 同时删除$this-&gt;db-&gt;reconnect();声明
    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2017-06-21
    • 2015-10-31
    相关资源
    最近更新 更多