90 lines
2.6 KiB
PHP
90 lines
2.6 KiB
PHP
<?php
|
|
/**
|
|
* Created by PhpStorm.
|
|
* User: bahamut
|
|
* Date: 2018/1/26
|
|
* Time: 14:15
|
|
*/
|
|
|
|
/**
|
|
* 每日自动任务
|
|
*/
|
|
require_once dirname(__DIR__) . '/common/config.inc.php';
|
|
require_once dirname(__DIR__) . '/common/DatabaseHelper.php';
|
|
|
|
/**
|
|
* @note 打印日志
|
|
* @param mixed $message
|
|
* @return bool
|
|
*/
|
|
function OutputDebugMessage($message)
|
|
{
|
|
if (is_object($message) || is_array($message))
|
|
$message = JsonObjectToJsonString($message);
|
|
|
|
$nowdate = date('Y-m-d');
|
|
$nowtime = date('H:i:s');
|
|
$pathname = Characet(dirname($_SERVER['SCRIPT_FILENAME']) . '/debug/autotask', 'gbk');
|
|
$filename = "{$pathname}/{$nowdate}.log";
|
|
$message = Characet($message, 'gbk');
|
|
if (!is_dir($pathname))
|
|
mkdir($pathname, 0777, true); // 修复不能同时创建俩个不存在的文件夹的bug
|
|
|
|
if ($file = fopen($filename, 'a+')) {
|
|
if (mb_strstr($message, PHP_EOL, false, USEDCHARSET) != PHP_EOL)
|
|
$message .= PHP_EOL;
|
|
|
|
fwrite($file, "{$nowtime} ====> {$message}");
|
|
fclose($file);
|
|
return true;
|
|
} else
|
|
return false;
|
|
}
|
|
|
|
date_default_timezone_set('Asia/Shanghai');
|
|
|
|
/**
|
|
* @var IPDOHelper $db
|
|
*/
|
|
$db = new PDODelegator(DATABASE_TYPE);
|
|
if (!$db->Connect(MASTER_HOSTNAME, MASTER_HOSTPORT, MASTER_DATABASE, MASTER_USERNAME, MASTER_PASSWORD, MASTER_CHARSET)) {
|
|
$log = JsonObjectToJsonString($db->GetErrors());
|
|
OutputDebugMessage($log);
|
|
die($log);
|
|
}
|
|
|
|
$db->BeginTransaction(); /// 启动事务
|
|
$sync_date = date('Y-m-d', strtotime(isset($_REQUEST['sync_date']) ? $_REQUEST['sync_date'] : '-1 days')); // 前一天
|
|
|
|
try {
|
|
// 1、从数据库获取自动执行脚本
|
|
if ($commands = $db->request('select `sql`, `params`, `table` from ct_report_ext_sql where status = ?;', 1)) {
|
|
$commands = json_decode(json_encode($commands), true);
|
|
} else {
|
|
throw new Exception('从数据库获取自动执行脚本失败', -1);
|
|
}
|
|
|
|
// 2、循环执行脚本
|
|
foreach ($commands as $key => $value) {
|
|
// 删除前一天原有的数据
|
|
if (!$db->execute(/** @lang text */
|
|
'delete from `' . $value['table'] . '` where date_format(`time`, \'%Y-%m-%d\') = ?;', $sync_date)
|
|
)
|
|
throw new Exception($db->geterrorinfo() . '(' . __LINE__ . ')', intval($db->geterrorcode()));
|
|
|
|
// 插入前一天的数据
|
|
if (!$db->execute($value['sql'], $sync_date))
|
|
throw new Exception($db->geterrorinfo() . '(' . __LINE__ . ')', intval($db->geterrorcode()));
|
|
}
|
|
|
|
$db->Commit(); /// 提交事务
|
|
$log = 'success!';
|
|
} catch (Exception $Exception) /// 异常处理
|
|
{
|
|
$db->Rollback(); /// 事务回滚
|
|
$log = JsonObjectToJsonString(array('code' => $Exception->getCode(), 'info' => $Exception->getMessage(),));
|
|
OutputDebugMessage($log);
|
|
}
|
|
|
|
die($log);
|