Azure Functions 的計時器觸發程序Timer trigger for Azure Functions

本文說明如何在 Azure Functions 中使用計時器觸發程序。This article explains how to work with timer triggers in Azure Functions. 計時器觸發程序可讓您依照排程執行函式。A timer trigger lets you run a function on a schedule.

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

封裝Packages

Microsoft.Azure.WebJobs.Extensions NuGet 套件中提供計時器觸發程序。The timer trigger is provided in the Microsoft.Azure.WebJobs.Extensions NuGet package. 套件的原始程式碼位於 azure-webjobs-sdk-extensions GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

對於 Azure Functions 2.x 版中的本機開發,此套件會自動註冊為繫結擴充功能For local development in Azure Functions version 2.x, the package is automatically registered as a binding extension. 對於 Functions 1.x 和 2.x 中的 C# 類別庫開發,此套件會自動安裝在專案中For C# class library development in Functions 1.x and 2.x, the package is automatically installed in the project.

請注意,原始程式碼會遵循 WebJobs SDK 版本編號:WebJobs SDK 2.x 版相當於 Azure Functions 1.x,所以 Functions 1.x 程式碼位於存放庫的 v2.x 分支中。Note that source code follows WebJobs SDK version numbering: WebJobs SDK version 2.x is equivalent to Azure Functions 1.x, so Functions 1.x code is in the v2.x branch in the repository. 主要和開發人員分支會包含 Web Jobs 3.x 的程式碼,這與 Functions 2.x 相同。Master and dev branches contain code for Web Jobs 3.x, which is the same as Functions 2.x.

範例Example

請參閱特定語言的範例:See the language-specific example:

C# 範例C# example

下列範例示範每五分鐘執行一次的 C# 函式The following example shows a C# function that runs every five minutes:

[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
{
    if(myTimer.IsPastDue)
    {
        log.Info("Timer is running late!");
    }
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}

C# 指令碼範例C# script example

下列範例示範 function.json 檔案中的計時器觸發程序繫結,以及使用此繫結的 C# 指令碼函式The following example shows a timer trigger binding in a function.json file and a C# script function that uses the binding. 此函式會寫入一項記錄,指出此函式引動過程是否由遺失的排程項目所造成。The function writes a log indicating whether this function invocation is due to a missed schedule occurrence.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "schedule": "0 */5 * * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}

以下是 C# 指令碼程式碼:Here's the C# script code:

public static void Run(TimerInfo myTimer, TraceWriter log)
{
    if(myTimer.IsPastDue)
    {
        log.Info("Timer is running late!");
    }
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}" );  
}

F# 範例F# example

下列範例示範 function.json 檔案中的計時器觸發程序繫結,以及使用此繫結的 F# 指令碼函式The following example shows a timer trigger binding in a function.json file and an F# script function that uses the binding. 此函式會寫入一項記錄,指出此函式引動過程是否由遺失的排程項目所造成。The function writes a log indicating whether this function invocation is due to a missed schedule occurrence.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "schedule": "0 */5 * * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}

以下是 F# 指令碼程式碼:Here's the F# script code:

let Run(myTimer: TimerInfo, log: TraceWriter ) =
    if (myTimer.IsPastDue) then
        log.Info("F# function is running late.")
    let now = DateTime.Now.ToLongTimeString()
    log.Info(sprintf "F# function executed at %s!" now)

JavaScript 範例JavaScript example

下列範例示範 function.json 檔案中的計時器觸發程序繫結,以及使用此繫結的 JavaScript 函式The following example shows a timer trigger binding in a function.json file and a JavaScript function that uses the binding. 此函式會寫入一項記錄,指出此函式引動過程是否由遺失的排程項目所造成。The function writes a log indicating whether this function invocation is due to a missed schedule occurrence.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "schedule": "0 */5 * * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}

以下是 JavaScript 指令碼程式碼:Here's the JavaScript script code:

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if(myTimer.isPastDue)
    {
        context.log('Node.js is running late!');
    }
    context.log('Node.js timer trigger function ran!', timeStamp);   

    context.done();
};

屬性Attributes

C# 類別庫中,使用 TimerTriggerAttributeIn C# class libraries, use the TimerTriggerAttribute.

該屬性的建構函式會採用 CRON 運算式或是 TimeSpanThe attribute's constructor takes a CRON expression or a TimeSpan. 僅當函式應用程式是在 App Service 方案中執行時,您才可以使用 TimeSpanYou can use TimeSpan only if the function app is running on an App Service plan. 下列範例顯示 CRON 運算式:The following example shows a CRON expression:

[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
{
    if (myTimer.IsPastDue)
    {
        log.Info("Timer is running late!");
    }
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}

組態Configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 TimerTrigger 屬性。The following table explains the binding configuration properties that you set in the function.json file and the TimerTrigger attribute.

function.json 屬性function.json property 屬性內容Attribute property 說明Description
typetype n/an/a 必須設定為 "timerTrigger"。Must be set to "timerTrigger". 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/a 必須設定為 "in"。Must be set to "in". 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
namename n/an/a 代表函式程式碼中計時器物件的變數名稱。The name of the variable that represents the timer object in function code.
scheduleschedule ScheduleExpressionScheduleExpression CRON 運算式TimeSpan 值。A CRON expression or a TimeSpan value. TimeSpan 只能用於 App Service 方案上執行的函式應用程式。A TimeSpan can be used only for a function app that runs on an App Service Plan. 您可以將排程運算式放在應用程式設定中,並將此屬性設定為以 % 符號包裝的應用程式設定名稱,如此範例所示:"%ScheduleAppSetting%"。You can put the schedule expression in an app setting and set this property to the app setting name wrapped in % signs, as in this example: "%ScheduleAppSetting%".
runOnStartuprunOnStartup RunOnStartupRunOnStartup 如果為 true,當執行階段啟動時,會叫用函式。If true, the function is invoked when the runtime starts. 例如,當函式應用程式因無活動而處於閒置狀態後再甦醒時、For example, the runtime starts when the function app wakes up after going idle due to inactivity. 當函式應用程式因函式變更而重新啟動時,以及當函式應用程式相應放大時,執行階段便會啟動。因此 runOnStartup 應該幾乎不會設定為 true,因為它會使程式碼在極度無法預期的時間執行。when the function app restarts due to function changes, and when the function app scales out. So runOnStartup should rarely if ever be set to true, as it will make code execute at highly unpredictable times.
useMonitoruseMonitor UseMonitorUseMonitor 設定為 truefalse 以表示是否應該監視排程。Set to true or false to indicate whether the schedule should be monitored. 排程監視會使排程持續進行,以協助確保即使在函式應用程式執行個體重新啟動時,排程也能正確地持續運作。Schedule monitoring persists schedule occurrences to aid in ensuring the schedule is maintained correctly even when function app instances restart. 如果未明確設定,則循環間隔大於 1 分鐘的排程之預設值為 trueIf not set explicitly, the default is true for schedules that have a recurrence interval greater than 1 minute. 若為每分鐘觸發超過一次的排程,預設值為 falseFor schedules that trigger more than once per minute, the default is false.

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

使用量Usage

叫用計時器觸發程序函式時,計時器物件會傳遞至函式。When a timer trigger function is invoked, the timer object is passed into the function. 下列 JSON 是計時器物件的範例表示法。The following JSON is an example representation of the timer object.

{
    "Schedule":{
    },
    "ScheduleStatus": {
        "Last":"2016-10-04T10:15:00+00:00",
        "LastUpdated":"2016-10-04T10:16:00+00:00",
        "Next":"2016-10-04T10:20:00+00:00"
    },
    "IsPastDue":false
}

當目前函式引動過程晚於排程時,IsPastDue 屬性為 trueThe IsPastDue property is true when the current function invocation is later than scheduled. 例如,函式應用程式重新啟動可能會導致遺漏引動過程。For example, a function app restart might cause an invocation to be missed.

CRON 運算式CRON expressions

Azure Functions 計時器觸發程序的 CRON 運算式包含六個欄位:A CRON expression for the Azure Functions timer trigger includes six fields:

{second} {minute} {hour} {day} {month} {day-of-week}

每個欄位可以具備下列類型的值:Each field can have one of the following types of values:

類型Type 範例Example 觸發時間When triggered
特定值A specific value "0 5 * * * *""0 5 * * * *" 於 hh:05:00,其中 hh 是每小時 (一小時一次)at hh:05:00 where hh is every hour (once an hour)
所有值 (*)All values (*) "0 * 5 * * *""0 * 5 * * *" 於每天 5:mm:00,其中 mm 是小時中的每一分鐘 (一天 60 次)at 5:mm:00 every day, where mm is every minute of the hour (60 times a day)
範圍 (- 運算子)A range (- operator) "5-7 * * * * *""5-7 * * * * *" 於 hh:mm:05、hh:mm:06 和 hh:mm:07,其中 hh: mm 是每小時的每一分鐘 (一分鐘 3 次)at hh:mm:05,hh:mm:06, and hh:mm:07 where hh:mm is every minute of every hour (3 times a minute)
一組值 (, 運算子)A set of values (, operator) "5,8,10 * * * * *""5,8,10 * * * * *" 於 hh:mm:05、hh:mm:08 和 hh:mm:10,其中 hh: mm 是每小時的每一分鐘 (一分鐘 3 次)at hh:mm:05,hh:mm:08, and hh:mm:10 where hh:mm is every minute of every hour (3 times a minute)
間隔值 (/ 運算子)An interval value (/ operator) "0 */5 * * * *""0 */5 * * * *" 於 hh:05:00、hh:10:00、hh:15:00 以此類推,直到 hh:55:00,其中 hh 是每小時 (一小時 12 次)at hh:05:00, hh:10:00, hh:15:00, and so on through hh:55:00 where hh is every hour (12 times an hour)

CRON 範例CRON examples

以下是您可以在 Azure Functions 中使用於計時器觸發程序的一些 CRON 運算式範例。Here are some examples of CRON expressions you can use for the timer trigger in Azure Functions.

範例Example 觸發時間When triggered
"0 */5 * * * *""0 */5 * * * *" 每隔 5 分鐘一次once every five minutes
"0 0 * * * *""0 0 * * * *" 每小時開始時一次once at the top of every hour
"0 0 */2 * * *""0 0 */2 * * *" 每隔 2 小時一次once every two hours
"0 0 9-17 * * *""0 0 9-17 * * *" 上午 9 點到下午 5 點之間每隔一小時一次once every hour from 9 AM to 5 PM
"0 30 9 * * *""0 30 9 * * *" 每天上午 9:30at 9:30 AM every day
"0 30 9 * * 1-5""0 30 9 * * 1-5" 每個工作日上午 9:30at 9:30 AM every weekday

注意

您可以在線上找到 CRON 運算式範例,但其中大部分都會省略 {second} 欄位。You can find CRON expression examples online, but many of them omit the {second} field. 如果您複製其中一個運算式,請新增遺漏的 {second} 欄位。If you copy from one of them, add the missing {second} field. 通常您在該欄位中需要零,而非星號。Usually you'll want a zero in that field, not an asterisk.

CRON 時區CRON time zones

CRON 運算式中的數字代表時間和日期,而非時間範圍。The numbers in a CRON expression refer to a time and date, not a time span. 例如,hour 欄位中的 5 代表上午 5:00,而非每隔 5 小時。For example, a 5 in the hour field refers to 5:00 AM, not every 5 hours.

CRON 運算式使用的預設時區是國際標準時間 (UTC)。The default time zone used with the CRON expressions is Coordinated Universal Time (UTC). 若要讓 CRON 運算式以另一個時區為基礎,請為名為 WEBSITE_TIME_ZONE 的函式應用程式建立應用程式設定。To have your CRON expression based on another time zone, create an app setting for your function app named WEBSITE_TIME_ZONE. 將值設定為所需的時區名稱,如 Microsoft 時區索引中所示。Set the value to the name of the desired time zone as shown in the Microsoft Time Zone Index.

例如,美加東部標準時間是 UTC-05:00。For example, Eastern Standard Time is UTC-05:00. 若要讓計時器觸發程序在每天上午 10:00 (美加東部標準時間) 觸發,您可以使用說明 UTC 時區的下列 CRON 運算式︰To have your timer trigger fire at 10:00 AM EST every day, use the following CRON expression that accounts for UTC time zone:

"schedule": "0 0 15 * * *",

或者為名為 WEBSITE_TIME_ZONE 的函式應用程式建立應用程式設定,並將值設為美加東部標準時間Or create an app setting for your function app named WEBSITE_TIME_ZONE and set the value to Eastern Standard Time. 然後使用下列 CRON 運算式:Then uses the following CRON expression:

"schedule": "0 0 10 * * *",

時間範圍TimeSpan

TimeSpan 只能用於 App Service 方案上執行的函式應用程式。A TimeSpan can be used only for a function app that runs on an App Service Plan.

不同於 CRON 運算式,TimeSpan 值會指定每個函式引動過程之間的時間間隔。Unlike a CRON expression, a TimeSpan value specifies the time interval between each function invocation. 如果函式在執行時間超過指定時間間隔之後完成,計時器會立即再次叫用函式。When a function completes after running longer than the specified interval, the timer immediately invokes the function again.

以字串表示,當 hh 低於 24 時,TimeSpan 格式為 hh:mm:ssExpressed as a string, the TimeSpan format is hh:mm:ss when hh is less than 24. 當前兩個數字為 24 或更高時,格式為 dd:hh:mmWhen the first two digits are 24 or greater, the format is dd:hh:mm. 這裡有一些範例:Here are some examples:

範例Example 觸發時間When triggered
"01:00:00""01:00:00" 每小時every hour
"00:01:00""00:01:00" 每分鐘every minute
"24:00:00""24:00:00" 每 24 天every 24 days

向外延展Scale-out

如果函式應用程式相應放大至多個執行個體,則只有計時器觸發函式的單一執行個體會在所有執行個體中執行。If a function app scales out to multiple instances, only a single instance of a timer-triggered function is run across all instances.

共用儲存體的函式應用程式Function apps sharing Storage

如果您在多個函式應用程式中共用儲存體帳戶,請確定每個函式應用程式在 host.json 中具有不同的 idIf you share a Storage account across multiple function apps, make sure that each function app has a different id in host.json. 您可以省略 id 屬性或將每個函式應用程式的 id 手動設定為不同的值。You can omit the id property or manually set each function app's id to a different value. 計時器觸發程序會使用儲存體鎖定,以確保當函數應用程式相應放大至多個執行個體時,只會有一個計時器執行個體。The timer trigger uses a storage lock to ensure that there will be only one timer instance when a function app scales out to multiple instances. 如果兩個函式應用程式共用相同的 id,且每一個都是使用計時器觸發程序,則只有一個計時器會執行。If two function apps share the same id and each uses a timer trigger, only one timer will run.

重試行為Retry behavior

不同於佇列觸發程序,計時器觸發程序在函式失敗後並不會重試。Unlike the queue trigger, the timer trigger doesn't retry after a function fails. 當函式失敗時,需等到排程上的下一次觸發,才會再次呼叫函式。When a function fails, it is't called again until the next time on the schedule.

後續步驟Next steps