2017-11-17 183 views
1

我設置了多個觸發器,如:爲什麼Google Cloud Function在部署後多次運行全局功能?

exports.doSomething = functions.firestore.document('col/{doc}').onCreate(event => {}) 

比我有我想要運行時刻,當我部署一個功能。這看起來是這樣的:

now() 
function now(){ 
    console.log("running function") 
} 

而且我得到這個在我的日誌:

enter image description here

它爲什麼跑這麼多次,並得到其他函數調用?

的完整代碼,只是測試它和運行函數被調用4次,相同數量的觸發我已設置:

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 
const db = admin.firestore() 
var geoip = require('geoip-lite'); 

exports.z = functions.firestore.document('converasdassdtIP/{UID}').onCreate(event => { }) 
exports.x = functions.firestore.document('sads/{UID}').onCreate(event => { }) 
exports.n = functions.firestore.document('asdasasdsa/{UID}').onCreate(event => { }) 
exports.m = functions.firestore.document('converasdasddtIP/{UID}').onCreate(event => { }) 

now() 
function now(){ 
    console.log("running function") 
} 
+0

你的代碼在哪裏調用'now()'?你可以添加你的一些'function/index.js'到這個問題嗎? – Callam

+0

@Callam看到我的編輯 –

+0

每次觸發函數時,都會調用'now()'的調用,因爲它位於'index.js'文件的根範圍內,因此每個運行的雲功能都會看到登錄。你想用這個日誌實現什麼?你想什麼時候打印? – Callam

回答

4

雲功能,不提供了一種在運行一段代碼部署時間。您的功能顯然會多次運行,並且您應該預計它將運行甚至更​​多次,因爲新的服務器實例將與您的項目負載一起分配(和銷燬)。這就是雲端功能如何擴展。絕對不只有一個服務器實例處理您的所有請求。您應該期望任何全局代碼重複運行。

如果您想在部署完成後只運行一次代碼,請創建導出功能(可能是HTTPS)並在部署後觸發它。也許你可以編寫一個腳本來部署你的代碼,然後使用curl或你選擇的其他機制來觸發這個函數。