簡體   English   中英

有沒有辦法在cron中立即啟動一個作業,然后在執行完成后停止它?

[英]Is there a way to start a job immediately in cron and then stop it after the execution is completed?

我剛開始使用 cron,但找不到安排一次性工作的方法。 我所擁有的正在為我工​​作,但我想知道是否有更好的方法來實現它。

下面的代碼創建一個作業並在控制台中打印它已創建。 我每 1 秒設置一次計時器,但就在下面我用 1.5 秒進行睡眠以停止工作。

const express = require('express');
const cron = require('node-cron');
const router = express.Router();

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// Schedule a job on GET
router.get('/', (req, res, next) => {
  const job = cron.schedule(`*/1 * * * * *`, () => {
    console.log('job created');
  });
  sleep(1500).then(() => {
    job.stop();
  })
  
  return res.status(200).json({ message: 'scheduled'});
});

您可以構建如下所示的 cron 表達式。 "0 0 7 8 9 ? 2020" (seconds min hour dayOfMonth Month DayofWeek Year) ,這只會運行一次。 您需要根據您希望作業運行的第一天/時間構建此表達式。 如果需要立即運行,可以根據當前時間+一些秒緩沖區構建cron表達式

正如snp建議的那樣,我必須創建一個帶有最近日期加上幾秒的cron 表達式。 但同時,我也意識到包node-cron是完全不同cron ,盡管他們的重定向到相同的地方。

我是這樣解決的:

const express = require('express');
const cron = require('cron'); // <- change of package
const router = express.Router();
const cronJob = cron.CronJob; // <- get the cron job from the package

const getDateAsCronExpression = () => { ... }

// Schedule a job on GET
router.get('/', (req, res, next) => {
  const cronExpression = getDateAsCronExpression();
  var job = new cronJob(cronExpression, () => {
    console.log('job executed!');
  }, null, true, 'your_time_zone_here');
  
  return res.status(200).json({ message: 'scheduled'});
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM