Firebase CronJob 排程設定

Google Firebase Cloud Functions 終於支援 schedule 排程(類似 cronjob )執行了, 語法也是採用滿通用的 UNIX CRON 任務排程格式

JeffChang
3 min readJun 2, 2019
export const testScheduleFunction = functions
.region(config.REGION)
.pubsub.schedule('* * * * *')
.timeZone('Asia/Taipei')
.onRun(async (context) => {
console.log('This will be run every min!');
});

這裡就直接用 Friebase Cloud Functions 來說明吧!

上面的程式碼就是宣告排程執行的方法,

  • region 是指定 GCP 的主機地區,因為我把地區抽出來放到設定檔了,所以社這邊會看到我是用 config.REGION 的參數帶入,而主機地區我是使用日本東京的主機(asia-northeast1)。
  • pubsub 是觸發建立並且傳送訊息給 GCP 的 Cloud Pub/Sub 端點,讓 GCP 幫我們執行。
  • schedule 是設定排程的週期,上面程式碼是 * * * * * 代表意義是每分鐘執行一次,詳細的下文會說明。
  • timeZone 應該不需要說明了?沒有特別設定台灣時間的話,就會走預設的 UTC +0 時區。
  • onRun 就是執行排程 functions 裡頭要做的事情摟。

Schedule

先來看這張圖解說名(來源:Google Cloud 文件

擷取自Google Cloud 文件

這張圖滿一目瞭然的,其中這些欄位各自有定義有效的數字。

擷取自Google Cloud 文件

再用幾個範例說明應該會比較容易了解

  1. 每一分鐘 * * * * *
  2. 每一小時 0 * * * *
  3. 每天 0 0 * * *
  4. 每三個小時 0 */3 * * *
  5. 每週一的早上0900 0 9 * * 1

再依照自己所需要的時間去定義就好了。

這裡推薦一個找資料時發現的很好用的網站,https://crontab.guru/

在網站上面可以直接輸入格式,然後就會顯示他的週期給你看,就可以馬上知道你設定的語法是不是正確的。

以上。

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

JeffChang
JeffChang

Written by JeffChang

Java Backend Engineer In DDIM.

No responses yet

Write a response