2

I am developing a nodejs application that schedules multiple cron jobs. By the way I got an error when I try to cancel jobs.

The situation is like below.

  • I created multiple cron jobs using node-cron or node-schedule.
  • A few jobs's start time already passed then I tried to cancel all the cron jobs using a script.
  • I got an error like below. TypeError: testJob.destory is not a function

Could you help me to solve this issue?

cron module / cronManager.js

const cron = require("node-cron") 

// cron jobs
let testJob1
let testJob2
let testJob3

async function startCronjobs(cronTimes) {
  testJob1 = cron.schedule(cronTimes.testTime1, () => {
    console.log("test 1 job")
  }, {
    scheduled: true, 
    timezone: "America/New_York"
  })
  testJob1.start() 

testJob2 = cron.schedule(cronTimes.testTime2, () => {
    console.log("test 2 job")
  }, {
    scheduled: true, 
    timezone: "America/New_York"
  })
  testJob2.start() 

testJob3 = cron.schedule(cronTimes.testTime3, () => {
    console.log("test 3 job")
  }, {
    scheduled: true, 
    timezone: "America/New_York"
  })
  testJob3.start() 
}

async function destroyCronjobs() {
  console.log("============= Destroy node-cron Jobs ================")
  return new Promise((resolve, reject) => {
    if(testJob1 !== undefined && testJob1 !== null) testJob1.destory()
    if(testJob2 !== undefined && testJob2 !== null) testJob2.destory()
    if(testJob3 !== undefined && testJob3 !== null) testJob3.destory() 
  })
}

module.exports.destroyJobs = destroyCronjobs
module.exports.startCronJobs = startCronjobs

script / main.js

const cronManager = require("./cronManager")
const express = require("express") 
const router = express.Router() 

router.post("/start", wrapper(async (req, res) => {
    await cronManager.startCronjobs()
}))

router.post("/destroy", wrapper(async (req, res) => {
    await cronManager.destoryCronjobs()
}))

vcvcvcvc
  • 137
  • 4
  • 10

1 Answers1

1

You have an typo error in your code you have testJob1.destory() but it should be testJob.destroy()

destroy() will be stopped and completely destroy the scheduled task.

Assume that this the sample code, so that its missing some argument for cronManager.startCronjobs() and also this function not returning any promise to use await.

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34