|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- `Coravel`不仅可以执行后台定时程序,还具备队广播事件功能。
-
-
-
- 引用
-
- ```
- <PackageReference Include="Coravel" Version="3.1.0" />
- ```
-
-
-
- # 后台定时程序
-
- 如果执行后台定时程序,需要定义一个`IInvocable`对象
-
- ```
- public class RegisterDevices : IInvocable
- {
- ublic async System.Threading.Tasks.Task Invoke()
- {
-
- }
- }
- ```
-
-
-
- 注入到容器中
-
- ```
- services.AddScheduler();//计划
- services.AddQueue();//队列
- services.AddEvents();//广播
-
- services.AddTransient<RegisterDevices>();//注册IInvocable
- ```
-
- 在请求管道中配置 频率等行为
-
- ```
- var provider = app.ApplicationServices; ;//获取IServiceProvider
-
- provider.UseScheduler(s =>
- {
- #region 本地相关
-
- //更新所有模块的上传频率
- s.OnWorker("WRegisterDevices");//让任务之间并行不会有延时影响
- s.Schedule<RegisterDevices>()
- .Cron("*/1 * * * *")//每1分钟运行一次
- .PreventOverlapping("RegisterDevices");//当第一次执行不完,第二次就不执行
- })
-
- .OnError(exception =>
- {
- Console.WriteLine(exception.Message);
- });
- ```
-
- # 事件广播
-
- `Coravel`会把事件放队列中,依次执行。
-
- 定义事件。
-
- ```
- public class SceneExecuted : IEvent
- {
- public SceneArgs SceneArgs { get; set; }
-
- public SceneExecuted(SceneArgs sceneArgs)
- {
- SceneArgs = sceneArgs;
- }
- }
-
- public class SceneArgs
- {
- public string SceneId { get; set; }
- public string SceneScheduleId { get; set; }
- public string StartTime { get; set; }
- }
- ```
-
- 定义事件观察者。
-
- ```
- public class SceneExecuteListener : IListener<SceneExecuted>
- {
- public async System.Threading.Tasks.Task HandleAsync(SceneExecuted broadcasted)
- {
-
- }
- }
- ```
-
- 在容器中注册
-
- ```
- services.AddTransient<SceneExecuted>(); //IEvent
- services.AddTransient<SceneExecuteListener>();//IListener
- services.AddTransient<SceneArgs>();
- ```
-
- 在请求管道中定义事件行为
-
- ```
- //事件
- IEventRegistration registration = provider.ConfigureEvents();
-
- //场景的执行情况上传到云端,cloudgo=1时执行
- registration
- .Register<SceneExecuted>()
- .Subscribe<SceneExecuteListener>();
-
- //队列
- provider
- .ConfigureQueue()
- //.LogQueuedTaskProgress(Services.GetService<ILogger<IQueue>>())
- .OnError(exception =>
- {
- Console.WriteLine(exception.Message);
- });
- ```
-
- 在`appsettings.json`中定义队列间隔
-
- ```
- "Coravel": {
- "Queue": {
- "ConsummationDelay": 30 //队列项的等待时间
- }
- }
- ```
-
|