LoginSignup
1
0

More than 3 years have passed since last update.

Cloud Functions for Firebase の関数をスケジューラから定期的に呼び出す簡単な方法

Posted at

イントロ

Cloud Functions をスケジューラから呼び出す方法について。

以前 Cloud Functions for Firebase の関数をスケジューラから定期的に呼び出す という記事で、Cloud Functions for Firebaseを定期的に呼び出すのに、

  • functions.pubsub.topic('testTopic').onPublish(message => {..処理..}) という関数をつくって
  • gcloud のコマンドで、testTopicにPublishする処理をスケジュール登録

する方法を書きましたが、そのつづき。

もっと簡単に設定出来るようになってた(初めからあった??)

最近みたら、関数のスケジュール設定 にもっとシンプルな方法が。

まず以下は前回のやりかたです。

前回
function want_to_execute() {
  console.log('実行したいロジック!')
}

export const helloPubSub = functions.pubsub
.topic('testTopic').onPublish(message => {
  want_to_execute()
})

として、具体的なスケジュールは別途で登録していました。

コレを

今回
function want_to_execute() {
  console.log('実行したいロジック!')
}

export const helloPubSub = functions.pubsub
  .schedule('0 */1 * * *')
  .timeZone('Asia/Tokyo')
  .onRun(async context => {
    want_to_execute()
  })

というように、スケジュール指定とタイムゾーンを直接記述できるようです。簡単ですね。。
ちなみにココでOwn Codingしちゃっても、のちほど画面上で変更可能です。

さてデプロイして確認してみましょう。

$ npm run deploy

画面で確認してみると firebase-schedule-checkLicensePubSub-us-central1 というTopic待ちの関数がたしかに登録されています。

00.png

スケジューラは、そのTopicにPublishするようにスケジュール設定されていますね。
01.png

一応Topicをみてみると
02.png

このようにウラではTopicが自動作成されていました。ようするに既存の方式と同じ方式です。
つまりスケジュール情報をコード上に書く方法は、既存の書き方の syntactic sugar ってことがわかりました。。

おつかれさまでしたー。

参考 ちなみにコード上で関数のregionとかも指定出来た

備忘です。

export const helloPubSub = functions.pubsub.region('asia-northeast1')  ココ
  .schedule('0 */1 * * *')
  .timeZone('Asia/Tokyo')
  .onRun(async context => {
    want_to_execute()
  })

こんな感じに関数の稼働するregion指定なども可能でした。

関連リンク

1
0
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
1
0