网页:https://elsa-workflows.github.io/elsa-core/docs/guides-recurring-task
在本节中,我们将执行以下操作:
- 以编程方式定义一个工作流,使用TimerEvent活动每5秒自动执行一次。
让我们开始吧!
创建控制台项目
创建一个名为Elsa.Guides.RecurringTask.ConsoleApp的新.NET Core控制台项目,并添加以下软件包:
- Elsa.Core
- Elsa.Activities.Console
- Elsa.Activities.Timers
- Microsoft.Extensions.Hosting
定义工作流
创建一个名为RecurringTaskWorkflow的新类,并添加以下代码:
using System; using Elsa.Activities.Console.Activities; using Elsa.Activities.Timers.Activities; using Elsa.Expressions; using Elsa.Services; using Elsa.Services.Models; using NodaTime; namespace Elsa.Guides.RecurringTask.ConsoleApp { public class RecurringTaskWorkflow : IWorkflow { public void Build(IWorkflowBuilder builder) { builder .AsSingleton() .StartWith<TimerEvent>(x => x.TimeoutExpression = new LiteralExpression<TimeSpan>("00:00:05")) .Then<WriteLine>(x => x.TextExpression = new JavaScriptExpression<string>("`It's now ${new Date()}. Let's do this thing!`")); } } }View Code
在此,我们将此工作流程定义为单例。单例工作流将永远只运行一个实例。 在此示例中,这是合适的,因为我们不想每次计时器后台运行程序计时时都生成新的工作流实例。
更新Program程序
接下来,打开 Program.cs 并插入以下代码:
using System; using System.Threading.Tasks; using Elsa.Activities.Console.Activities; using Elsa.Activities.Console.Extensions; using Elsa.Activities.Timers.Extensions; using Elsa.Expressions; using Elsa.Extensions; using Elsa.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NodaTime; namespace Elsa.Guides.RecurringTask.ConsoleApp { class Program { static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureServices(ConfigureServices) .ConfigureLogging(logging => logging.AddConsole()) .UseConsoleLifetime() .Build(); using (host) { await host.StartAsync(); await host.WaitForShutdownAsync(); } } private static void ConfigureServices(IServiceCollection services) { services .AddWorkflows() .AddConsoleActivities() .AddTimerActivities(options => options.Configure(x => x.SweepInterval = Duration.FromSeconds(1))) .AddWorkflow<RecurringTaskWorkflow>(); } } }View Code
请注意,我们不必自己手动调用工作流。而是由 HostBuilder 构建的主机内部执行的后台任务来处理。
运行
执行以下命令运行程序:
dotnet run Elsa.Guides.RecurringTask.ConsoleApp.csproj
5秒后,你会看到如下输出:
It's now Tue Sep 17 2019 16:28:40 GMT+02:00. Let's do this thing! It's now Tue Sep 17 2019 16:28:46 GMT+02:00. Let's do this thing! It's now Tue Sep 17 2019 16:28:52 GMT+02:00. Let's do this thing!
总结
在本指南中,我们已经了解了如何设置使用 TimerEvent 活动触发的工作流。
源码
https://github.com/elsa-workflows/elsa-guides/tree/master/src/Elsa.Guides.RecurringTask.ConsoleApp