销毁node-cron作业或取消节点调度程序作业

问题描述 投票:1回答:1

我正在开发一个nodejs应用程序来安排多个cron作业。顺便说一句,当我尝试取消工作时,我遇到了错误。

情况如下。

  • 我使用node-cronnode-schedule创建了多个cron作业。
  • 一些作业的开始时间已经过去,然后我尝试使用脚本取消所有cron作业。
  • 我收到如下错误。 TypeError: testJob.destory is not a function

你能帮我解决这个问题吗?

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()
}))

javascript node.js cron node-cron
1个回答
0
投票

你的代码中有一个拼写错误,你有testJob1.destory()但它应该是testJob.destroy()

destroy()将被停止并完全破坏预定的任务。

假设这是示例代码,因此它缺少cronManager.startCronjobs()的一些参数,而且这个函数也没有返回任何promise来使用await

© www.soinside.com 2019 - 2024. All rights reserved.