KeepServerAwake.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Plugins;
  3. using MediaBrowser.Controller.Session;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Linq;
  7. using MediaBrowser.Common.Threading;
  8. namespace MediaBrowser.Server.Startup.Common.EntryPoints
  9. {
  10. public class KeepServerAwake : IServerEntryPoint
  11. {
  12. private readonly ISessionManager _sessionManager;
  13. private readonly ILogger _logger;
  14. private PeriodicTimer _timer;
  15. private readonly IServerApplicationHost _appHost;
  16. public KeepServerAwake(ISessionManager sessionManager, ILogger logger, IServerApplicationHost appHost)
  17. {
  18. _sessionManager = sessionManager;
  19. _logger = logger;
  20. _appHost = appHost;
  21. }
  22. public void Run()
  23. {
  24. _timer = new PeriodicTimer(obj =>
  25. {
  26. var now = DateTime.UtcNow;
  27. var nativeApp = ((ApplicationHost)_appHost).NativeApp;
  28. try
  29. {
  30. if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15))
  31. {
  32. nativeApp.PreventSystemStandby();
  33. }
  34. else
  35. {
  36. nativeApp.AllowSystemStandby();
  37. }
  38. }
  39. catch (Exception ex)
  40. {
  41. _logger.ErrorException("Error resetting system standby timer", ex);
  42. }
  43. }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  44. }
  45. public void Dispose()
  46. {
  47. if (_timer != null)
  48. {
  49. _timer.Dispose();
  50. _timer = null;
  51. }
  52. }
  53. }
  54. }