I'm trying to create a CRON for every minute in my Azure Function timer trigger.
As per the documentation I found this: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer#cron-examples
"0 */1 * * * *" doesn't run at all.
"*/1 * * * * *" does run every second.
Where am I going wrong?
function.json looks like this:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */1 * * * *"
}
],
"scriptFile": "../dist/TriggerWork/index.js"
}
I could reproduce your issue with {AzureWebJobsStorage} connection string entry in the local.settings.json is somehow mismatched in its format:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "{AzureWebJobsStorage}",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
For all triggers except for HTTP, a valid AzureWebJobsStorage connection string is required. The reason behind this has to do with scaling out to multiple VMs: If the function scales out to multiple VMs and has multiple instances, a storage account is needed to coordinate to ensure that only one instance of the timer trigger is running at a time. This poses some difficulty if you are trying to develop locally but, unfortunately, this is currently a limitation of the timer trigger.
For more details, you could refer to this similar issue.
Related
I have an Azure Function with a Timer trigger. The schedule is "*/6 * * * *" (running every six minutes). I cannot run it manually and it does not fire automatically. Below is my function.json:
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.31",
"configurationSource": "attributes",
"bindings": [
{
"type": "timerTrigger",
"schedule": "%TimerTriggerPeriod%",
"useMonitor": true,
"runOnStartup": false,
"name": "myTimer"
}
],
"disabled": false,
"scriptFile": "../bin/AccessChangeMonitoring.dll",
"entryPoint": "Microsoft.IT.Security.AccessChangeMonitoring.AccessChangeMonitoring.InitiateChangeMonitoring"
}
%TimerTriggerPeriod% is defined in my local.settings.json file ("TimerTriggerPeriod": "0 */6 * * * *"). Looking at the Application Function Count metric display on the dashboard, it shows that my function has been executed 0 times:
Below is my host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
},
"functionTimeout": "00:07:00"
}
Below is the function code:
[FunctionName("InitiateChangeMonitoring")]
public static async Task InitiateChangeMonitoring([TimerTrigger("%TimerTriggerPeriod%")] TimerInfo myTimer, ILogger log)
{
log.LogInformation("Change Monitoring started.");
// Reset the listing of app ids we need to retrieve delta role assignments for
oneAuthZAppIds = new List<string>();
await GetOneAuthZAppIdsAsync();
// Create the necessary Cosmos DB infastructure
await CreateDatabaseAsync();
await CreateContainerAsync();
await CreateDeltaAPICallDatabaseAsync();
await CreateDeltaAPICallContainerAsync();
await CreateManagerMappingDatabaseAsync();
await CreateManagerMappingContainerAsync();
// Compute the authentication token needed to access the PAP Service API
log.LogInformation("\nRetrieve PAPServiceAPIToken");
string PAPServiceAPIToken = await GetTokenAsync(Environment.GetEnvironmentVariable("OneAuthZAppUri"), Environment.GetEnvironmentVariable("OneAuthZAppId"),
PAPAuthenticationSecret);
log.LogInformation("PAPServiceAPIToken = " + PAPServiceAPIToken);
string GraphAPIAuthenticationToken = await GetTokenAsync(Environment.GetEnvironmentVariable("GraphAppUri"), Environment.GetEnvironmentVariable("GraphClientId"),
graphKey);
log.LogInformation("graphAPIAuthenticationToken = " + GraphAPIAuthenticationToken);
await runChangeMonitoringSystemAsync(PAPServiceAPIToken);
}
First, I notice you specify you are using local.settings.json to save the environment variable and at the same time you show the metric on azure.
So, I think the first problem why your azure function can not be triggered is because you don't set the environment variable on azure.
You should set in this place instead of local.settings.json (because when a function is deployed to Azure, it will never take environment variable from local.settings.json):
(Don't forget to save the edit.)
Second, as Ivan says, your format of cron is wrong. The format of timetrigger should be in this format:
{second} {minute} {hour} {day} {month} {day of week}
I have the following C# function code:
[FunctionName("UpdateCohortsByTenantFunction")]
[return: Queue("my-queue", Connection = "MyStorage")]
//note - I have tried both method decoration and parameter decoration
public static async Task Run([TimerTrigger("* * * * * *")]TimerInfo myTimer, IAsyncCollector<AudienceMessage> output)
{
//some logic
foreach (var audience in audiences)
{
await output.AddAsync(new AudienceMessage
{
AudienceId = audience.Id,
TenantId = tenant.Id
});
}
}
Which produces the following function.json:
{
"generatedBy": "Microsoft.NET.Sdk.Functions.Generator-1.0.6",
"configurationSource": "attributes",
"bindings": [
{
"type": "timerTrigger",
"schedule": "* * * * * *",
"useMonitor": true,
"runOnStartup": false,
"name": "myTimer"
}
],
"disabled": false,
"scriptFile": "../bin/MyApp.App.Tasks.Functions.dll",
"entryPoint": "MyApp.App.Tasks.Functions.UpdateCohortsByTenantFunction.Run"
}
According to the documentation here the json output should contain an binding to my queue with an "out" direction. Ie:
{
"type": "queue",
"direction": "out",
"name": "$return",
"queueName": "outqueue",
"connection": "MyStorageConnectionAppSetting",
}
When I try to run the queue via the npm tools (config described here), I get the following error:
Run: Microsoft.Azure.WebJobs.Host: Error indexing method 'UpdateCohortsByTenantFunction.Run'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'output' to type IAsyncCollector`1. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).
The documentation contains no references to binding via startup code. My understanding is that this is done via the attributes described in the Microsoft documentation linked above, and in my example code, but the error message suggests otherwise.
You should decorate your parameter with attribute, not return value:
public static async Task Run(
[TimerTrigger("* * * * * *")]TimerInfo myTimer,
[Queue("my-queue", Connection = "MyStg")] IAsyncCollector<AudienceMessage> output)
No output binding in function.json is to be expected. Attribute-defined bindings are not transferred to generated function.json. They will still work, don't worry.
I have a function app with the following code
public static void Run([TimerTrigger("*/5 * * * * *")]TimerInfo myTimer, TraceWriter log)
This executes my function every 5 seconds. In production I want the interval to be 30 seconds. After I publish the function to Azure it works and is run every 5 seconds.
On the top of the Integrate -page in the Function settings there is a message "Your app is currently in read-only mode because you have published a generated function.json. Changes made to function.json will not be honored by the Functions runtime" and the page is greyed out.
So how do I have different schedule for my timer function in development and production?
Make your schedule configurable. Declare it like this in code:
[TimerTrigger("%schedule%")]
Then add the development setting named schedule with value */5 * * * * * and production setting with value */30 * * * * *.
This should sum up the other answers given here:
Configure local settings
add a local.settings.json file to your project.
insert the following code:
{
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=XXXXXXXXXX;AccountKey=XXXXXXXXXX",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=XXXXXXXXXX;AccountKey=XXXXXXXXXX",
"schedule": "*/5 * * * * *",
"//": "put additional settings in here"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
},
"ConnectionStrings": {
"SQLConnectionString": "XXXXXXXXXX"
}
}
set the trigger attribute like
[TimerTrigger("%schedule%")]
Configure Azure
go to the Azure Portal and go to functions, click on your function and select Application settings
in the application setting select Add new setting
enter schedule as key and */30 * * * * * as value
click save on the top left
redeploy your function
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:
var rp = require('request-promise');
var request = require('request');
module.exports = function (context //need to get the url) {
and the function
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 */1 * * *"
}
],
"disabled": false
}
If your settings are relatively static (but you still don't want to hard code them), you may use app settings to store them, and then read e.g.
let url = process.env['MyUrl'];
If URL should be determined per request, you may use HTTP trigger and read the URL from query parameters:
let url = req.query.myurl;
I'm not sure what exactly you are trying to achieve with parameterized timer-triggered function.
Another possibility is if your parameters are stored somewhere in e.g. Azure Document DB (Cosmos).
You could still use a TimerTrigger to invoke the function, and include a DocumentDB input binding allowing you to query for the specific parameter values needed to execute the function.
Here's a C# example triggered by Timer, with a DocumentDB input binding. Note: I'm using the latest VS2017 Preview tooling for Azure functions.
[FunctionName("TimerTriggerCSharp")]
public static void Run(
[TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log,
[DocumentDB("test-db-dev", "TestingCollection", SqlQuery = "select * from c where c.doc = \"Test\"")] IEnumerable<dynamic> incomingDocuments)
{..}
With the following binding json:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
},
{
"type": "documentDB",
"name": "incomingDocuments",
"databaseName": "test-db-dev",
"collectionName": "TestingCollection",
"sqlQuery": "select * from c where c.docType = \"Test\"",
"connection": "my-testing_DOCUMENTDB",
"direction": "in"
}
],
"disabled": false
}
I have an Azure Function that I created in the Azure portal and now want to recreate it using the visual studio azure tooling associated with VS2017 Preview.
My function is Timer triggered, and also has an input binding for Azure DocumentDB (with a query) and an output binding to an Azure Service Bus queue.
Here's the functions.json definition from the portal:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
},
{
"type": "serviceBus",
"name": "outputQueue",
"queueName": "test-output-requests",
"connection": "send-refresh-request",
"accessRights_": "Send",
"direction": "out"
},
{
"type": "documentDB",
"name": "incomingDocuments",
"databaseName": "test-db-dev",
"collectionName": "TestingCollection",
"sqlQuery": "select * from c where c.docType = \"Test\"",
"connection": "my-testing_DOCUMENTDB",
"direction": "in"
}
],
"disabled": false
}
In VS2017, I create an Azure Function project, then a Azure function using the TimerTriggered template:
public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, TraceWriter log, ICollector<dynamic> outputQueue, IEnumerable<dynamic> incomingDocuments)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
//Inspect incomingDocuments .. push messages to outputQueue
}
Running locally, the timer is triggered as expected - but how do I recreate the input and output bindings in code? I'm not sure what attributes I should use, and what I need in json config files to wire it up.
Add reference to following nuget pacakge
https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.DocumentDB/
Add using Microsoft.Azure.WebJobs
Update the documentDb Parameter as follows (Add other properties as well)
[DocumentDB(ConnectionStringSetting = "")]IEnumerable<dynamic> incomingDocuments
Update the serviceBus Parameter as follows
[ServiceBus("test-output-requests",Connection = "ConnectionValue")]
Verify the generated function.json in the bin/functionName/function.json
Thanks,
Naren