鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8、使用Coravel执行后台定时程序.md 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. `Coravel`不仅可以执行后台定时程序,还具备队广播事件功能。
  2. 引用
  3. ```
  4. <PackageReference Include="Coravel" Version="3.1.0" />
  5. ```
  6. # 后台定时程序
  7. 如果执行后台定时程序,需要定义一个`IInvocable`对象
  8. ```
  9. public class RegisterDevices : IInvocable
  10. {
  11. ublic async System.Threading.Tasks.Task Invoke()
  12. {
  13. }
  14. }
  15. ```
  16. 注入到容器中
  17. ```
  18. services.AddScheduler();//计划
  19. services.AddQueue();//队列
  20. services.AddEvents();//广播
  21. services.AddTransient<RegisterDevices>();//注册IInvocable
  22. ```
  23. 在请求管道中配置 频率等行为
  24. ```
  25. var provider = app.ApplicationServices; ;//获取IServiceProvider
  26. provider.UseScheduler(s =>
  27. {
  28. #region 本地相关
  29. //更新所有模块的上传频率
  30. s.OnWorker("WRegisterDevices");//让任务之间并行不会有延时影响
  31. s.Schedule<RegisterDevices>()
  32. .Cron("*/1 * * * *")//每1分钟运行一次
  33. .PreventOverlapping("RegisterDevices");//当第一次执行不完,第二次就不执行
  34. })
  35. .OnError(exception =>
  36. {
  37. Console.WriteLine(exception.Message);
  38. });
  39. ```
  40. # 事件广播
  41. `Coravel`会把事件放队列中,依次执行。
  42. 定义事件。
  43. ```
  44. public class SceneExecuted : IEvent
  45. {
  46. public SceneArgs SceneArgs { get; set; }
  47. public SceneExecuted(SceneArgs sceneArgs)
  48. {
  49. SceneArgs = sceneArgs;
  50. }
  51. }
  52. public class SceneArgs
  53. {
  54. public string SceneId { get; set; }
  55. public string SceneScheduleId { get; set; }
  56. public string StartTime { get; set; }
  57. }
  58. ```
  59. 定义事件观察者。
  60. ```
  61. public class SceneExecuteListener : IListener<SceneExecuted>
  62. {
  63. public async System.Threading.Tasks.Task HandleAsync(SceneExecuted broadcasted)
  64. {
  65. }
  66. }
  67. ```
  68. 在容器中注册
  69. ```
  70. services.AddTransient<SceneExecuted>(); //IEvent
  71. services.AddTransient<SceneExecuteListener>();//IListener
  72. services.AddTransient<SceneArgs>();
  73. ```
  74. 在请求管道中定义事件行为
  75. ```
  76. //事件
  77. IEventRegistration registration = provider.ConfigureEvents();
  78. //场景的执行情况上传到云端,cloudgo=1时执行
  79. registration
  80. .Register<SceneExecuted>()
  81. .Subscribe<SceneExecuteListener>();
  82. //队列
  83. provider
  84. .ConfigureQueue()
  85. //.LogQueuedTaskProgress(Services.GetService<ILogger<IQueue>>())
  86. .OnError(exception =>
  87. {
  88. Console.WriteLine(exception.Message);
  89. });
  90. ```
  91. 在`appsettings.json`中定义队列间隔
  92. ```
  93. "Coravel": {
  94. "Queue": {
  95. "ConsummationDelay": 30 //队列项的等待时间
  96. }
  97. }
  98. ```