Google BigQuery - 自动执行Cron作业

时间:2015-06-12 12:55:51

标签: php cron google-bigquery

使用PHP,我可以手动运行BigQuery,但我需要BigQuery作为自动cron作业运行(没有Gmail登录)。我怎么做到这一点?感谢。

1 个答案:

答案 0 :(得分:3)

您需要在开发人员控制台中创建一个服务帐户,而不是从代码中使用。这是我们在cron文件中的代码。

你需要:

  • 已创建服务帐户(类似Google_Client
  • 您的密钥文件(...@developer.gserviceaccount.com
  • service_token_file_location(从握手中存储JSON的可写路径,它将有效1小时)

代码示例:

.p12

您可以使用以下方式获取结果:

function getGoogleClient($data = null) {
    global $service_token_file_location, $key_file_location, $service_account_name;
    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");

    $old_service_token = null;
    $service_token = @file_get_contents($service_token_file_location);
    $client->setAccessToken($service_token);
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials(
            $service_account_name, array(
        'https://www.googleapis.com/auth/bigquery',
        'https://www.googleapis.com/auth/devstorage.full_control'
            ), $key
    );
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
        $service_token = $client->getAccessToken();
    }
    return $client;
}

$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);

/**
 * @see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
 */
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);

$job->setConfiguration($config);

$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');

$queryConfig->setDestinationTable($destinationTable);

$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);

try {
//    print_r($job);
//    exit;
    $job = $bq->jobs->insert(PROJECT_ID, $job);

    $status = new Google_Service_Bigquery_JobStatus();
    $status = $job->getStatus();
//    print_r($status);
    if ($status->count() != 0) {
        $err_res = $status->getErrorResult();
        die($err_res->getMessage());
    }
} catch (Google_Service_Exception $e) {
    echo $e->getMessage();
    exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
    $state = $status['state'];

echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;

您可以在此处看到可用于其他BigQuery调用的类。当您阅读该文件时,请知道该文件是从其他来源生成的,因此对于PHP来说它看起来很奇怪,您需要学习阅读它以便能够使用它中的方法。

https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php

像:

  • Google_Service_Bigquery_TableRow

同时查看[php]和[google-bigquery]标记的问题 https://stackoverflow.com/questions/tagged/google-bigquery+php