KeepServerAwake.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 System.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 Timer _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 Timer(obj =>
  25. {
  26. var now = DateTime.UtcNow;
  27. if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15))
  28. {
  29. KeepAlive();
  30. }
  31. }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  32. }
  33. private void KeepAlive()
  34. {
  35. var nativeApp = ((ApplicationHost)_appHost).NativeApp;
  36. try
  37. {
  38. nativeApp.PreventSystemStandby();
  39. }
  40. catch (Exception ex)
  41. {
  42. _logger.ErrorException("Error resetting system standby timer", ex);
  43. }
  44. }
  45. public void Dispose()
  46. {
  47. if (_timer != null)
  48. {
  49. _timer.Dispose();
  50. _timer = null;
  51. }
  52. }
  53. }
  54. }