rufus-scheduler 적용

This commit is contained in:
2025-04-19 06:02:27 +09:00
parent f7131c827f
commit cf3dae63f3
4 changed files with 28 additions and 38 deletions

View File

@@ -1,56 +1,41 @@
# polling_service.rb
require "rufus-scheduler"
module Modbus
class PollingService
class << self
def start
return if $modbus_polling_threads.any?(&:alive?)
$modbus_polling_threads << start_thread
end
return if defined?(@scheduler) && @scheduler&.running?
def stop
$modbus_polling_threads.each { |t| t.kill if t.alive? }
$modbus_polling_threads.clear
puts "Modbus polling service 중지됨"
end
puts "[#{Time.current}] Modbus polling service 시작됨 (Rufus)"
@scheduler = Rufus::Scheduler.new
def running?
$modbus_polling_threads.any?(&:alive?)
end
private
def start_thread
Thread.new { run_polling_loop }
end
def run_polling_loop
puts "Modbus polling service 시작됨"
last_logged = nil
loop do
begin
now = Time.now
current = [ now.hour, now.min ]
current_time = format("%02d:%02d", current[0], current[1])
puts "# current time: #{current_time}.#{now.sec}"
if current != last_logged
puts "시간 변경 감지됨: #{current_time}"
schedule = Schedule.find_by(hour: current[0], minute: current[1])
apply_schedule(schedule) if schedule
last_logged = current
end
sleep 1
rescue => e
puts "[#{Time.current}] #{file} 에러: #{e.message}"
end
@scheduler.cron "0 * * * * *" do
now = Time.now
current_time = format("%02d:%02d", now.hour, now.min)
puts "# current time: #{current_time}.#{now.sec}"
schedule = Schedule.find_by(hour: now.hour, minute: now.min)
apply_schedule(schedule) if schedule
end
end
def stop
@scheduler&.shutdown
puts "[#{Time.current}] Modbus polling service 중지됨"
end
def running?
@scheduler&.running?
end
private
def apply_schedule(schedule)
if schedule.is_active
run_script("on_off.rb", "0", "[Schedule] ON")
run_script(
"serial.rb",
(schedule.temperature * 10).to_i.to_s,
"[Schedule] #{schedule.hour}:#{schedule.minute} → #{schedule.temperature}°C"
"[Schedule] #{format('%02d:%02d', schedule.hour, schedule.minute)} → #{schedule.temperature}°C"
)
else
run_script("on_off.rb", "1", "[Schedule] OFF")