【发布时间】:2020-11-01 09:07:14
【问题描述】:
我将用一个例子来说明这一点。
假设我有一个 MySQL 数据库,我在其中放置要上传到 S3 的文件的路径,以及一个状态列,其中每个文件都归因于 pending 或 uploaded 字符串。
我有一个 PHP 脚本 upload.php,我可以使用 php upload.php 运行它,并在脚本运行时接收记录到终端的输出。我想设置一个 cron 作业,以一定的时间间隔运行脚本,比如每 30 分钟一次,每次查询数据库并处理具有pending 状态的文件以供上传。
现在,我希望能够跟踪脚本的进度,无论其在前端的当前状态如何(如果当前数据库中没有待处理的项目)。
虽然我会很感激有关如何执行此操作的任何具体建议,但我的问题也是关于最佳实践 - 意思是,执行此操作的正确方法是什么?
这是一个这样的脚本示例(它使用 Joshcam MysqliDb)
// Get items with a pending status
function get_items_queue() {
global $db;
$cols = Array ("id", "filename");
$db->where('status = "pending"');
return $db->get('files', null, $cols);
}
// Upload items to S3
function UploadToS3($filename) {
if (empty($filename)) {
return false;
}
include_once('/s3/aws-autoloader.php');
$s3 = new S3Client($somearray); // Some S3 credentials here
// Print status
echo $filename . ' is uploading';
$uploaded = $s3->putObject($somearray); // Uploading to S3
if ($s3->doesObjectExist($s3_bucket, $filename)) {
// Print status
echo $filename . ' was uploaded';
} else {
// Print status
echo 'There has been an issue while uploading ' . $filename;
}
}
// Run the script
$queue_items = get_items_queue();
foreach ($queue_items as $key => $item) {
$upload = UploadToS3($item['filename']);
// Some function here that changes the status column for the uploaded item to 'uploaded'
if ($upload) {
set_item_queue_status($item['id']);
}
}
【问题讨论】:
-
在哪里追踪?
-
是否要通过web请求cron作业执行的状态日志?
-
某种日志的前端视图(输出脚本的回声),或者,我正在考虑一个 jQuery/ajax 解决方案,但我不确定这是否是“正确的”方式”来做到这一点。