透過命令列開發:
安裝完畢後請確認 az
、func
和 azurite
指令可以被正常執行,如果失敗請重新安裝或手動將 az
和 func
的目錄加入環境變數。
檢查各項工具的版本是否夠新:
首先啟動 Azure Storage 的模擬器,因為
執行 func init
命令,在 CronApp 的資料夾中建立 .NET 的 Azure Functions 專案:
將基於 Timer trigger
的 Function 新增至專案:
Timer trigger
依賴 NCrontab 套件,這個套件需要透過 Azure Storage
儲存一個檔案當作 lock,確保當 Function App 擴展到多個實例時,只使用唯一一個 timer 實例。
此外,如果兩個 Function App 共享相同的 identifying configuration,並且個別使用一個 timer,則只有一個 timer 會運作。
所以接下來先啟動 Azurite 以在本機模擬 Azure Storage:
在上述指令中透過 --location
選項,Azurite 所產生的暫存檔會放在 azurite_workspace
中。
在執行程式之前,修改一下 CronApp.cs
的規則使其每 5 秒觸發一次。
"*/5 * * * * *"
。TimerTriggerAttribute
的原始碼在 WebJobs.Extensions/Extensions/Timers/TimerTriggerAttribute.cs。執行程式:
每 5 秒 CronApp 會輸出一條訊息:
流程與 初探 Azure Functions 一樣:
佈署到 Azure 後透過 log stream 查看 CronApp 是否有被觸發:
NCrontab 已經兩年沒有新的 commit 了,但是 WebJobs.Extensions/Extensions/Timers 還持續有在更新,所以 Azure 團隊應該有在持續維護。