TimerWorkService.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  7. using TEAMModelOS.SDK.DI;
  8. using TEAMModelOS.Service.Services.Learn.Interfaces;
  9. namespace TEAMModelOS.Service.Services.Learn.Implements
  10. {
  11. public class TimerWorkService: ITimerWorkService
  12. {
  13. private readonly AzureCosmosFactory _cosmos;
  14. public TimerWorkService(AzureCosmosFactory cosmos)
  15. {
  16. _cosmos = cosmos;
  17. }
  18. public void TimerWork<T>(long startTime, int status , Dictionary<string, object> dict) where T : ID
  19. {
  20. System.Timers.Timer aTimer = new System.Timers.Timer();
  21. // Create a timer with a two second interval.
  22. long time = Math.Abs(startTime - new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds());
  23. aTimer = new System.Timers.Timer(time);
  24. // Hook up the Elapsed event for the timer.
  25. aTimer.Elapsed += async (sender, e) => await OnTimedEventAsync<T>(_cosmos,status, dict);
  26. aTimer.AutoReset = false;
  27. aTimer.Enabled = true;
  28. }
  29. public static async Task OnTimedEventAsync<T>(AzureCosmosFactory _cosmos, int status, Dictionary<string, object> dict) where T : ID
  30. {
  31. List<T> homeWorks = await _cosmos.FindByDict<T>(dict);
  32. if (homeWorks.IsNotEmpty())
  33. {
  34. PropertyInfo propertyInfo = homeWorks[0].GetType().GetProperty("status");
  35. for (int i = 0; i < homeWorks.Count; i++)
  36. propertyInfo.SetValue(homeWorks[i], status);
  37. await _cosmos.SaveOrUpdateAll<T>(homeWorks);
  38. }
  39. }
  40. }
  41. }