From a85bd2b5ab2944dc239a6e9dac219b5f8ba48680 Mon Sep 17 00:00:00 2001 From: Bill Rossi Date: Sun, 17 Aug 2025 06:46:32 -0400 Subject: [PATCH] Replace homebrew scheduling logic with Rufus --- lib/lesson.rb | 26 ++++++++++++++++---------- test/test_lesson.rb | 18 ++++++------------ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/lib/lesson.rb b/lib/lesson.rb index 825ad8a..2c21ddd 100644 --- a/lib/lesson.rb +++ b/lib/lesson.rb @@ -1,3 +1,5 @@ +require "rufus-scheduler" + DEFAULT_LESSON_PLAN = [ [15, "login and catch up on the week"], [45, "review chapter vocab and grammar"], @@ -6,30 +8,34 @@ DEFAULT_LESSON_PLAN = [ ] class Lesson - attr_reader :lesson_plan, :channel, :thread, :running + attr_reader :lesson_plan, :channel, :thread, :running, :scheduler - def initialize(lesson_plan=DEFAULT_LESSON_PLAN) + def initialize(lesson_plan=DEFAULT_LESSON_PLAN, scheduler: Rufus::Scheduler.new) @lesson_plan = lesson_plan @running = false + @scheduler = scheduler end def stop! - thread.kill if thread - @running = false + @scheduler.shutdown end def start!(channel) - stop! - @channel = channel - @thread = Thread.new do - @running = true - lesson_plan.each do |time, message| + lesson_plan.each_with_index do |(time, message), index| + offset = lesson_plan.map(&:first)[0..index - 1].sum(0) + offset = 0 if index == 0 + scheduler.in "#{offset}m" do channel.send_message "#{time} minutes to #{message}" - sleep(time * 60) end + end + + end_offset = lesson_plan.map(&:first).sum(0) + scheduler.in "#{end_offset}m" do channel.send_message "Lesson over!" @running = false end + + @running = true end def running? diff --git a/test/test_lesson.rb b/test/test_lesson.rb index fcde514..7738510 100644 --- a/test/test_lesson.rb +++ b/test/test_lesson.rb @@ -3,20 +3,14 @@ require "minitest/autorun" class TestLesson < Minitest::Test def setup - @lesson = Lesson.new [[0.1 / 60, "test the thing"], [0.1 / 60, "finish testing"]] + @scheduler = Minitest::Mock.new end def test_start - @channel = Minitest::Mock.new - @channel.expect(:send_message, nil) { |msg| msg.include? "to test the thing" } - @channel.expect(:send_message, nil) { |msg| msg.include? "to finish testing" } - @channel.expect(:send_message, nil) { |msg| msg == "Lesson over!" } - assert_equal false, @lesson.running - @lesson.start!(@channel) - sleep(0.5) - # gonna be impossible to thread this needle - # assert_equal true, @lesson.running - sleep(0.5) - assert_equal false, @lesson.running + @lesson = Lesson.new [[1, "test the thing"], [3, "finish testing"]], scheduler: @scheduler + @scheduler.expect(:in, nil) { |time| time == "0m" } + @scheduler.expect(:in, nil) { |time| time == "1m" } + @scheduler.expect(:in, nil) { |time| time == "4m" } + @lesson.start! nil end end