简体   繁体   English

在本地运行一次计时器触发的 Azure 函数的最简单方法是什么?

[英]What is the simplest way to run a timer-triggered Azure Function locally once?

I have a few C# Azure Functions that run on a schedule using timer triggers .我有一些使用计时器触发器按计划运行的 C# Azure 函数。 I've set them up like so, where %TimerSchedule% refers to a cron expression in the app settings:我已经像这样设置它们,其中%TimerSchedule%指的是应用程序设置中的 cron 表达式:

public static void Run([TimerTrigger("%TimerSchedule%")]TimerInfo myTimer, TraceWriter log)

During development, I often want to run the functions locally using Azure Functions Tools for Visual Studio + Azure Functions Core Tools.在开发过程中,我经常想使用 Azure Functions Tools for Visual Studio + Azure Functions Core Tools 在本地运行函数。 But when I hit F5 to debug the function locally it (usually) doesn't run immediately.但是当我按 F5 在本地调试该功能时,它(通常)不会立即运行。 Instead, it starts waiting for the next occurrence as per the timer schedule.相反,它会根据计时器计划开始等待下一次发生。 So for example, if my cron expression says to run daily at 8PM, I'd have to wait until 8PM for the function to actually run on my machine.例如,如果我的 cron 表达式说每天晚上 8 点运行,那么我必须等到晚上 8 点才能让函数在我的机器上真正运行。

So my question is: What is the simplest and best way to make a function run once locally?所以我的问题是:让函数在本地运行一次的最简单和最好的方法是什么?

Things I have tried or considered:我尝试过或考虑过的事情:

  1. Use a more frequent timer schedule just for local development为本地开发使用更频繁的计时器计划
    • This is OK but not perfect – you still have to wait a little bit unless it's very frequent, and if it's very frequent then the function might run multiple times.这没问题,但并不完美——除非非常频繁,否则您仍然需要稍等片刻,如果非常频繁,则该函数可能会运行多次。 This is what I'm doing now.这就是我现在正在做的事情。
  2. Write a console app or unit test that directly calls the function's Run() method编写直接调用函数的Run()方法的控制台应用程序或单元测试
    • This isn't 100% straightforward because you have to provide TimerInfo and TraceWriter arguments to Run() – and I've found surprisingly little documentation for that.这不是 100% 简单的,因为您必须向Run()提供TimerInfoTraceWriter参数——而且我发现这方面的文档非常少。

Microsoft's Strategies for testing your code in Azure Functions page is not very helpful on this topic – it only mentions timer triggers as a way to test other trigger types. Microsoft 的在 Azure Functions 中测试代码的策略页面对这个主题不是很有帮助——它只提到了计时器触发器作为测试其他触发器类型的一种方式。

In a perfect world, I'd hit F5 and the function would immediately run once – just like developing a "normal" .NET app.在一个完美的世界里,我按下 F5 并且该函数会立即运行一次——就像开发一个“普通”的 .NET 应用程序一样。

I had the same question, and used the DEBUG-flag to have the RunOnStartup only while debugging:我有同样的问题,并使用 DEBUG 标志仅在调试时使用 RunOnStartup:

        public static void Run(
            [TimerTrigger("* 0 7 * * 1-5"
#if DEBUG
            , RunOnStartup=true
#endif
            )]TimerInfo myTimer, TraceWriter log)
        {

You could perhaps use the RunOnStartup flag as documented here .您也许可以使用此处记录的RunOnStartup标志。 It doesn't quite meet your brief regarding it only running once, but it should at least execute it locally once the app has started.它不完全符合您关于它只运行一次的简要说明,但它至少应该在应用程序启动后在本地执行它。

 /// Gets or sets a value indicating whether the function should be invoked /// immediately on startup. After the initial startup run, the function will /// be run on schedule thereafter.

Example using attribute binding:使用属性绑定的示例:

[TimerTrigger("%TimerSchedule%", RunOnStartup = true)]TimerInfo myTimer

From https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#non-http-triggered-functions来自https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#non-http-triggered-functions

Non-HTTP triggered functions非 HTTP 触发函数

For all kinds of functions other than HTTP triggers and webhooks, you can test your functions locally by calling an administration endpoint.对于 HTTP 触发器和 webhook 以外的所有类型的函数,您可以通过调用管理端点在本地测试您的函数。 Calling this endpoint with an HTTP POST request on the local server triggers the function.在本地服务器上使用 HTTP POST 请求调用此端点会触发该函数。 You can optionally pass test data to the execution in the body of the POST request.您可以选择将测试数据传递给 POST 请求正文中的执行。 This functionality is similar to the Test tab in the Azure portal.此功能类似于 Azure 门户中的“测试”选项卡。

You call the following administrator endpoint to trigger non-HTTP functions:您调用以下管理员端点来触发非 HTTP 函数:

http://localhost:{port}/admin/functions/{function_name}

To pass test data to the administrator endpoint of a function, you must supply the data in the body of a POST request message.要将测试数据传递给函数的管理员端点,您必须在 POST 请求消息的正文中提供数据。 The message body is required to have the following JSON format:消息正文需要具有以下 JSON 格式:

{
    "input": "<trigger_input>"
}

If you are using VS Code, use the Azure Functions extension :如果您使用的是 VS Code,请使用Azure Functions 扩展

  1. Hit F5 to enter debug mode, this starts the function app.按 F5 进入调试模式,这将启动函数应用程序。
  2. Go to the Azure icon in the Activity bar.转到活动栏中的 Azure 图标。
  3. Under Local Project , find the function you want to run, right click, and select "Execute Function Now".Local Project下,找到要运行的函数,右键单击,然后选择“Execute Function Now”。

Check out this MS quickstart guide .查看此 MS 快速入门指南

Using postman should do the trick.使用邮递员应该可以解决问题。 Follow the below steps to Run or debug you Timer Trigger Locally.按照以下步骤在本地运行或调试您的计时器触发器。

1 . 1. RUN your Project.运行您的项目。

  1. Open Postman and past this url http://localhost:{port}/admin/functions/{function_name}打开 Postman 并通过这个 url http://localhost:{port}/admin/functions/{function_name}

  2. Make sure to use a POST Method with Json body of { "input": "" }确保使用带有 { "input": "" } 的 Json 主体的 POST 方法

  3. Press SEND.按发送。

You Should receive a response of 202.您应该收到 202 的响应。

I had the same question.我有同样的问题。 I fixed it with a Unittest.我用单元测试修复了它。 Indeed you need to stub out the TraceWriter and the TimerInfo.实际上,您需要删除 TraceWriter 和 TimerInfo。

Here some code how I did this.这里有一些代码我是如何做到的。

TimerInfo:定时器信息:

public class ScheduleStub : TimerInfo
{
    public ScheduleStub(TimerSchedule schedule, ScheduleStatus status, bool isPastDue = false) : base(schedule, status, isPastDue)
    {
    }
}

And the TraceWriter:和 TraceWriter:

 public class TraceWriterStub : TraceWriter
{
    protected TraceLevel _level;
    protected List<TraceEvent> _traces;

    public TraceWriterStub(TraceLevel level) : base(level)
    {
        _level = level;
        _traces = new List<TraceEvent>();
    }

    public override void Trace(TraceEvent traceEvent)
    {
        _traces.Add(traceEvent);
    }

    public List<TraceEvent> Traces => _traces;
}

Start your function with this curl command使用此 curl 命令启动您的函数

curl --request POST -H "Content-Type:application/json" --data '{"input":""}'  http://localhost:7071/admin/functions/{function_name}

The input data is required, without it the function won't be triggered.输入数据是必需的,没有它将不会触发该功能。

Another approach is to trigger manually the function from Postman:另一种方法是从 Postman 手动触发该功能:
Manually run a non HTTP-triggered function . 手动运行非 HTTP 触发的函数

POST /admin/functions/<function name> HTTP/1.1
Host: localhost:<port>
Content-Type: application/json

{}

For me, it looks like that on postman for a timerTrigger function called Function1 :对我来说,它看起来像邮递员上一个名为Function1timerTrigger函数: 在此处输入图像描述

Just add another function with HTTP trigger type within the same class, add your code, or call your Run method from that function and invoke it from your browser.只需在同一类中添加另一个具有 HTTP 触发器类型的函数,添加代码,或从该函数调用 Run 方法并从浏览器调用它。

Be sure to comment/remove that function when deployed to prod, or you will have the ability to trigger the function via HTTP calls in prod.确保在部署到 prod 时注释/删除该函数,否则您将能够通过 prod 中的 HTTP 调用触发该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 定时器触发的 function 在 Azure function 应用程序(C#) - Timer-triggered function in Azure function app (C#) 具有定时器触发的 Azure 功能的令牌缓存 - Token Cache with Timer-Triggered Azure Functions 计时器触发的Azure功能未在计划的时间触发,并且因Azure存储超时异常而失败 - Timer-triggered Azure Function not triggered on scheduled time and failed with Azure storage timeout exception 如果 function 的实例已经在执行,定时器触发的 Azure function 是否会执行? - Does a timer-triggered Azure function execute if an instance of the function is already executing? 如何在计时器触发的函数上强制执行单例行为? - how to enforce singleton behavior on a timer-triggered function? 在Window OS / VS中每5分钟运行一次命令的最简单方法是什么? - What is the simplest way to run some command once every 5 min in Window OS / VS? 我可以在我的asp.net mvc网站触发的特定日期运行一次Azure功能吗? - Can I run a Azure function once on a specific date triggered by my asp.net mvc site? 定时器触发单元测试 Azure Function:提供测试数据 - Unit Tests for timer triggered Azure Function: provide test data 如何在本地测试/运行 azure 次 function - How to test/run azure times function locally 部署后,Azure 函数中的依赖注入失败但在本地工作 - Dependency Injection failing in Azure function once deployed but works locally
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM