8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cloud function for firebaseで定期実行

Posted at

手順

特に難しいことは何もない。

  • いつもどおりfirebase initでfunctionsを作る
  • functions.pubsub.schedule().onRun()で関数を作る
  • deploy

本家の解説はここ

有償プランである必要があるが、アカウント毎に3つまで無償らしい。
GCP側のUIでもある程度いじれるみたい。

実装

下記のような感じ。

index.js
const functions = require('firebase-functions');

exports.cron = functions.pubsub.schedule('every 1 minutes') //('* * * * *') cron風にも書ける
    .timeZone('Asia/Tokyo')
    .onRun((context) => {
        console.log("hello");
        console.log(context);
        return 0; //Function returned undefined, expected Promise or value 防止
    });

その他

contextの内容を出力してみたが、特に役立ちそうな情報はないみたい。
timestampが取れるので実行時間を記録したいとか、条件分岐したいとかに使えるかな。

{ eventId: '854843810028592',
  timestamp: '2019-11-23T21:45:00.067Z',
  eventType: 'google.pubsub.topic.publish',
  resource: 
   { service: 'pubsub.googleapis.com',
     name: 'projects/project-id/topics/firebase-schedule-cron-us-central1',
     type: 'type.googleapis.com/google.pubsub.v1.PubsubMessage' },
  params: {} }
    
8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?