InMemoryBackgroundJobStore.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections.Concurrent;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Abp.Timing;
  7. namespace Abp.BackgroundJobs
  8. {
  9. /// <summary>
  10. /// In memory implementation of <see cref="IBackgroundJobStore"/>.
  11. /// It's used if <see cref="IBackgroundJobStore"/> is not implemented by actual persistent store
  12. /// and job execution is enabled (<see cref="IBackgroundJobConfiguration.IsJobExecutionEnabled"/>) for the application.
  13. /// </summary>
  14. public class InMemoryBackgroundJobStore : IBackgroundJobStore
  15. {
  16. private readonly ConcurrentDictionary<long, BackgroundJobInfo> _jobs;
  17. private long _lastId;
  18. /// <summary>
  19. /// Initializes a new instance of the <see cref="InMemoryBackgroundJobStore"/> class.
  20. /// </summary>
  21. public InMemoryBackgroundJobStore()
  22. {
  23. _jobs = new ConcurrentDictionary<long, BackgroundJobInfo>();
  24. }
  25. public Task<BackgroundJobInfo> GetAsync(long jobId)
  26. {
  27. return Task.FromResult(_jobs[jobId]);
  28. }
  29. public Task InsertAsync(BackgroundJobInfo jobInfo)
  30. {
  31. jobInfo.Id = Interlocked.Increment(ref _lastId);
  32. _jobs[jobInfo.Id] = jobInfo;
  33. return Task.FromResult(0);
  34. }
  35. public Task<List<BackgroundJobInfo>> GetWaitingJobsAsync(int maxResultCount)
  36. {
  37. var waitingJobs = _jobs.Values
  38. .Where(t => !t.IsAbandoned && t.NextTryTime <= Clock.Now)
  39. .OrderByDescending(t => t.Priority)
  40. .ThenBy(t => t.TryCount)
  41. .ThenBy(t => t.NextTryTime)
  42. .Take(maxResultCount)
  43. .ToList();
  44. return Task.FromResult(waitingJobs);
  45. }
  46. public Task DeleteAsync(BackgroundJobInfo jobInfo)
  47. {
  48. _jobs.TryRemove(jobInfo.Id, out _);
  49. return Task.FromResult(0);
  50. }
  51. public Task UpdateAsync(BackgroundJobInfo jobInfo)
  52. {
  53. if (jobInfo.IsAbandoned)
  54. {
  55. return DeleteAsync(jobInfo);
  56. }
  57. return Task.FromResult(0);
  58. }
  59. }
  60. }