【问题标题】:destroy a node-cron job or cancel a node-scheduler job销毁 node-cron 作业或取消 node-scheduler 作业
【发布时间】:2019-07-28 21:36:28
【问题描述】:

我正在开发一个调度多个 cron 作业的 nodejs 应用程序。 顺便说一句,当我尝试取消作业时出现错误。

情况如下。

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

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

cron 模块/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

脚本/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】:

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

destroy() 将被停止并彻底销毁预定任务。

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

【讨论】:

  • 如果有一个工作已经开始,然后我试图破坏这个工作呢?
  • 会破坏的,把testJob1.destory()改成testJob.destroy()
  • 我试过了,还是一样。我只是重写我的代码以在这里显示它。所以类型错误不是问题。
  • 然后更新您的问题
  • 我解决了这个问题。问题是类型问题。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 2021-06-18
  • 2020-10-15
  • 2022-10-08
  • 2013-05-27
  • 2020-08-29
  • 2015-07-29
相关资源
最近更新 更多