1
0

Job2TimedService.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Admin.Core.Common.Helpers;
  2. using Microsoft.Extensions.Hosting;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Admin.Core.Tasks
  8. {
  9. public class Job2TimedService : IHostedService, IDisposable
  10. {
  11. private Timer _timer;
  12. // 这里可以注入
  13. public Job2TimedService()
  14. {
  15. }
  16. public Task StartAsync(CancellationToken cancellationToken)
  17. {
  18. Console.WriteLine("Job 2 is starting.");
  19. _timer = new Timer(DoWork, null, TimeSpan.Zero,
  20. TimeSpan.FromSeconds(60 * 60 * 2));//两个小时
  21. return Task.CompletedTask;
  22. }
  23. private void DoWork(object state)
  24. {
  25. ConsoleHelper.WriteWarningLine($"Job 2: {DateTime.Now}");
  26. }
  27. public Task StopAsync(CancellationToken cancellationToken)
  28. {
  29. Console.WriteLine("Job 2 is stopping.");
  30. _timer?.Change(Timeout.Infinite, 0);
  31. return Task.CompletedTask;
  32. }
  33. public void Dispose()
  34. {
  35. _timer?.Dispose();
  36. }
  37. }
  38. }