LoginSignup
0
1

More than 1 year has passed since last update.

cloud schedulerをfunctionから操作する

Last updated at Posted at 2021-09-21

概要

GCPコンソールからではなく、Webクライアントから cloud schedulerを操作する方法の一つとしてfunctionから呼び出してみるメモ。

やり方

cloud schedulerの操作は google-cloud/scheduler ライブラリを使えば利用できます。

webアプリから呼び出すには以下の方法

  • 直接APIを叩く
  • functionとして実装して呼び出す

直接叩く場合は、サーバにデフォルトの認証情報(環境変数 GOOGLE_APPLICATION_CREDENTIALS)を仕込んでおく、もしくはプログラム内で認証情報としてサービスアカウント、キー情報などを渡してあげる必要があります。

今回はfunctionとして実装し、もともと紐づけられているサービスアカウント情報を使ってAPIを実行するようにします。

functionの実装

ライブラリにjobを作るサンプルがあるので、今回は既存のjobを一時停止するAPIを叩くfunctionを作ります。

先に npm install @google-cloud/schedulerを実行しておきます。

functionのコードは以下の通り

import * as functions from "firebase-functions";
import { app } from "firebase-admin";
import { CloudSchedulerClient } from "@google-cloud/scheduler";
import { RuntimeOptions } from "./options/runtimeOptions";

module.exports = functions
  .region("asia-northeast1")
  .https
  .onCall(async (data, context) => {

    const client = new CloudSchedulerClient();
    const projectId = app().options.projectId;

    try {
      const jobPath = client.jobPath(projectId, "asia-northeast1", "firebase-schedule-someapi-asia-northeast1");
      const request = { name: jobPath };
      const ret = await client.pauseJob(request);

      console.log(ret);
      return true;

    } catch (e) {
      console.log(e.message);
      return false;
    }

  });

一時停止は pauseJob という関数を実行します。引数に PauseJobRequest として name を渡します。
name にジョブ名を指定すれば良いと思っていたのですが、ずっとエラーになっておりなんだろ。。と思っていたら、jobPath 関数を使ってパスを生成して引き渡す必要があったようです。
ドキュメントではPauseJobRequestのnameプロパティの説明として、「PauseJobRequest name」としか書いてないのでわかりづらすぎ。。

pauseJobの戻り値には以下のようなjob情報が渡されます。

[
  {
    name: 'projects/<projectId>/locations/<region>/jobs/firebase-schedule-someapi-asia-northeast1',
    description: '',
    userUpdateTime: { seconds: '1631762543', nanos: 0 },
    state: 'ENABLED',
    status: { details: [], code: 0, message: '' },
    scheduleTime: { seconds: '1632330000', nanos: 582680000 },
    lastAttemptTime: { seconds: '1632243600', nanos: 372395000 },
    retryConfig: null,
    schedule: '0 2 * * *',
    timeZone: 'Asia/Tokyo',
    attemptDeadline: null,
    pubsubTarget: {
      attributes: [Object],
      topicName: 'projects/<projectId>/topics/firebase-schedule-someapi-asia-northeast1',
      data: <Buffer >
    },
    target: 'pubsubTarget'
  },
  null,
  null
]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1