Skip to content

Commit

Permalink
Skip missed schedules
Browse files Browse the repository at this point in the history
This is to avoid running tasks multiple times on next schedule.
  • Loading branch information
akadusei committed Dec 3, 2023
1 parent b594db9 commit 406b83e
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased] -

### Fixed
- Skip missed schedules to avoid running tasks multiple times on next schedule

## [0.17.1] - 2023-12-02

### Fixed
Expand Down
9 changes: 9 additions & 0 deletions spec/mel/task_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ describe Mel::Task do
Mel::PeriodicTask.find(id).try(&.attempts.> 0).should be_true
end
end

it "skips missed schedules" do
SendEmailJob.run_every(1.hour, address: "aa@bb.cc")

Timecop.travel(10.hours.from_now) do
Mel.start_and_stop
Mel::Task.find_lte(Time.local, -1).should be_nil
end
end
end

describe "#enqueue" do
Expand Down
2 changes: 1 addition & 1 deletion src/mel/task/log_helpers.cr
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ abstract class Mel::Task
end

private def log_failed : Nil
attempts_str = 1 == attempts ? "attempt" : "attempts"
attempts_str = first_attempt? ? "attempt" : "attempts"

Mel.log.error &.emit(
"Task failed after #{attempts} #{attempts_str}",
Expand Down
9 changes: 9 additions & 0 deletions src/worker/task.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ abstract class Mel::Task

spawn(name: id) do
log_running
set_run_time
job.run
rescue error
log_errored(error)
Expand Down Expand Up @@ -48,6 +49,14 @@ abstract class Mel::Task
do_after_run(false)
end

private def set_run_time
self.time = Time.local if first_attempt?
end

private def first_attempt?
1 == attempts
end

macro inherited
def self.find_pending(count : Int, *, delete : Bool = false) : Array(self)?
return if count.zero?
Expand Down

0 comments on commit 406b83e

Please sign in to comment.