您需要使用jobstatus和doBackground()。 首先,您需要初始化傳輸。這是通過將任務發送到後臺並向用戶發送作業句柄來完成的。您可以通過yourserver.com/api/file-transfer調用此方法,並且必須使用fileurl集發送POST請求。答案是一個json對象。
<?php
// use composer for slim
require_once "vendor/autoload.php";
$app = new \Slim\Slim();
// init file transfer
$app->post('/file-transfer', function() use ($app) {
$resp = array();
try {
// get file url
$fileurl = $app->request->post('fileurl');
$data = json_encode(array("fileurl"=>$fileurl);
// send to gearman
$client = new GearmanClient();
$client->addServer();
// store the gearman handle and send the task to the background
$jobHandle = $client->doBackground("fileUpload", $data);
if ($client->returnCode() != GEARMAN_SUCCESS) throw new Exception("Could not add the job to the queue.", 1);
$resp["msg"] = "File upload queued";
$resp["handle"] = $jobHandle;
} catch(Exception $e) {
// some error handling
$resp["msg"] = "There occured a strange error.";
$resp["error"] = true;
} finally {
$response = $app->response();
$response['Content-Type'] = 'application/json';
$response->status(200);
$response->body(json_encode($resp));
}
});
?>
在第二個步驟,用戶需要查詢與作業處理服務器(這是他第一次調用接收):
$app->post('/file-status', function() use ($app) {
$jobHandle = $app->request->params('handle');
$resp = array();
try {
// ask for job status
$client = new GearmanClient();
$client->addServer();
$stat = $client->jobStatus($jobHandle);
if (!$stat[0]) { // it is done
$resp["msg"] = "Transfer completed.";
} else {
$resp["msg"] = "Transfer in progress.";
$w = (float)$stat[2]; // calculate the percentage
$g = (float)$stat[3];
$p = ($g>0)?$w/g*100:0;
$resp["percentage"] = $p;
}
} catch(Exception $e) {
// some error handling
$resp["msg"] = "There occured a strange error.";
$resp["error"] = true;
} finally {
$response = $app->response();
$response['Content-Type'] = 'application/json';
$response->status(200);
$response->body(json_encode($resp));
}
});
在第二個請求,你有$統計陣列從$ client-> jobStatus()。 $ stats [0]告訴你作業是否爲gearman服務器所知。第二步檢查它是否正在運行,並使用三到四(2/3)來計算轉移的百分比(您需要自己設置這些值!)。
來源
2015-08-18 15:57:24
Jan
是的一些代碼真的會有幫助。我無法發送回覆,然後繼續進行回覆 –
我明白了,但是,我希望在文件上傳完成後向用戶回覆回覆。然後開始一個新的過程(處理上傳的文件),我想向其顯示用戶的狀態。狀態不應該是爲文件上傳的API –
不幸的是,[回調不適用於後臺作業](http://stackoverflow.com/questions/21656299/gearman-addtaskbackground-complete-callback-doesnot-fire) Gearman的。所以一個可能的解決方案是使用[jquery ajax](http://api.jquery.com/jquery.ajax/)並每隔5到10秒輪詢一次服務器,直到處理完成。 – Jan