Skip to content

Commit

Permalink
Prevent possibility to launch same job multiple times simultaneously (#1
Browse files Browse the repository at this point in the history
)
  • Loading branch information
kibertoad authored Jan 20, 2021
1 parent 5c4cae6 commit 95c4a08
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/engines/simple-interval/SimpleIntervalJob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export class SimpleIntervalJob extends Job {
start(): void {
const time = toMsecs(this.schedule)

// Avoid starting duplicates and leaking previous timers
if (this.timer) {
this.stop()
}

this.timer = setInterval(() => {
this.task.execute()
}, time)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "toad-scheduler",
"version": "1.0.1",
"version": "1.0.2",
"license": "MIT",
"description": "In-memory Node.js job scheduler",
"maintainers": [
Expand Down
23 changes: 23 additions & 0 deletions test/toadScheduler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,29 @@ describe('ToadScheduler', () => {
scheduler.stop()
})

it('correctly handles adding job twice', () => {
let counter = 0
const scheduler = new ToadScheduler()
const task = new Task('simple task', () => {
counter++
})
const job = new SimpleIntervalJob(
{
milliseconds: 10,
},
task
)

scheduler.addSimpleIntervalJob(job)
scheduler.addSimpleIntervalJob(job)

expect(counter).toBe(0)
jest.advanceTimersByTime(20)
expect(counter).toBe(2)

scheduler.stop()
})

it('correctly stops jobs', () => {
let counter = 0
const scheduler = new ToadScheduler()
Expand Down

0 comments on commit 95c4a08

Please sign in to comment.