countdown.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. countdown = countdown or {}
  2. countdown.modpath = minetest.get_modpath("hb4")
  3. countdown.quit = false
  4. local color = minetest.get_color_escape_sequence("#ffff00")
  5. function countdown.step(data)
  6. -- Halt when done.
  7. if countdown.quit then
  8. return
  9. end
  10. data = data or {hour = -1, min = -1, sec = -1}
  11. -- Current time, as a number.
  12. local ct = os.time()
  13. local cd = os.date("!*t")
  14. -- Datetime of next shutdown.
  15. assert(countdown.time)
  16. local nd = countdown.time
  17. local nt = os.time(nd)
  18. -- If our restart time is in the past, we're done.
  19. if nt <= ct then
  20. local message = "# Server: RESTART IMMINENT - WAITING FOR OS SIGNAL."
  21. chat_logging.log_server_message(message)
  22. minetest.chat_send_all(color .. message)
  23. countdown.quit = true
  24. return
  25. end
  26. assert(nt >= ct)
  27. local rt = os.difftime(nt, ct)
  28. local rd = os.date("!*t", rt)
  29. local report = false
  30. local delay = 60
  31. -- Calculate how long until next public message.
  32. do
  33. -- Report on every hour change.
  34. if data.hour ~= rd.hour then
  35. report = true
  36. end
  37. -- Report every minute once there are 10 or less minutes.
  38. if rd.hour == 0 and rd.min <= 10 and data.min ~= rd.min then
  39. report = true
  40. end
  41. -- Report every second of the last 20 seconds.
  42. if rd.hour == 0 and rd.min == 0 and rd.sec <= 20 then
  43. report = true
  44. end
  45. -- Reduce delay to 5 seconds once there are 10 minutes remaining to restart.
  46. if rd.hour == 0 and rd.min <= 10 then
  47. delay = 5
  48. end
  49. -- And reduce to 1 second when there are 20 or less seconds remaining.
  50. if rd.hour == 0 and rd.min == 0 and rd.sec <= 20 then
  51. delay = 1
  52. end
  53. -- Record time of last timecheck.
  54. data.hour = rd.hour
  55. data.min = rd.min
  56. data.sec = rd.sec
  57. end
  58. if report then
  59. local message = "# Server: Nightly restart in: " .. string.format("%02d:%02d:%02d", rd.hour, rd.min, rd.sec) .. "."
  60. chat_logging.log_server_message(message)
  61. minetest.chat_send_all(color .. message)
  62. end
  63. -- Wait for next check.
  64. minetest.after(delay, countdown.step, data)
  65. end
  66. if not countdown.registered then
  67. -- Calculate time to next shutdown.
  68. local cd = os.date("!*t")
  69. -- Should be 06:00:00 of next day.
  70. local nd = table.copy(cd)
  71. nd.day = nd.day + 1
  72. nd.hour = 6
  73. nd.min = 0
  74. nd.sec = 0
  75. nd = os.date("!*t", os.time(nd))
  76. countdown.time = nd
  77. minetest.after(60, countdown.step, {})
  78. countdown.registered = true
  79. end