1
0

TaskSchedulerServiceExtensions.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using FreeScheduler;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System;
  5. using ZhonTai.Admin.Core.Configs;
  6. namespace ZhonTai.Admin.Tools.TaskScheduler;
  7. public static class TaskSchedulerServiceExtensions
  8. {
  9. public static IServiceProvider ServiceProvider { get; private set; }
  10. /// <summary>
  11. /// 添加任务调度
  12. /// </summary>
  13. /// <param name="services"></param>
  14. /// <param name="configureOptions"></param>
  15. public static void AddTaskScheduler(this IServiceCollection services, Action<TaskSchedulerOptions> configureOptions = null)
  16. {
  17. ServiceProvider = services.BuildServiceProvider();
  18. var options = new TaskSchedulerOptions()
  19. {
  20. FreeSql = ServiceProvider.GetService<IFreeSql>()
  21. };
  22. configureOptions?.Invoke(options);
  23. var freeSql = options.FreeSql;
  24. freeSql.CodeFirst
  25. .ConfigEntity<TaskInfo>(a =>
  26. {
  27. a.Name("ad_task");
  28. a.Property(b => b.Id).IsPrimary(true);
  29. a.Property(b => b.Body).StringLength(-1);
  30. a.Property(b => b.Interval).MapType(typeof(string));
  31. a.Property(b => b.IntervalArgument).StringLength(1024);
  32. a.Property(b => b.Status).MapType(typeof(string));
  33. a.Property(b => b.CreateTime).ServerTime(DateTimeKind.Local);
  34. a.Property(b => b.LastRunTime).ServerTime(DateTimeKind.Local);
  35. })
  36. .ConfigEntity<TaskLog>(a =>
  37. {
  38. a.Name("ad_task_log");
  39. a.Property(b => b.Exception).StringLength(-1);
  40. a.Property(b => b.Remark).StringLength(-1);
  41. a.Property(b => b.CreateTime).ServerTime(DateTimeKind.Local);
  42. });
  43. options.ConfigureFreeSql?.Invoke(freeSql);
  44. var dbConfig = ServiceProvider.GetService<DbConfig>();
  45. if (dbConfig.SyncStructure)
  46. {
  47. freeSql.CodeFirst.SyncStructure<TaskInfo>();
  48. freeSql.CodeFirst.SyncStructure<TaskLog>();
  49. }
  50. if(options.TaskHandler != null)
  51. {
  52. //开启任务
  53. var scheduler = new Scheduler(options.TaskHandler);
  54. services.AddSingleton(scheduler);
  55. }
  56. }
  57. /// <summary>
  58. /// 使用任务调度
  59. /// </summary>
  60. /// <param name="app"></param>
  61. public static void UseTaskScheduler(this IApplicationBuilder app)
  62. {
  63. ServiceProvider = app.ApplicationServices;
  64. }
  65. }