0

cron を使い始めたばかりですが、1 回限りのジョブをスケジュールする方法が見つかりません。私が持っているものは私のために働いていますが、それを達成するためのより良い方法があるかどうか知りたい.

以下のコードは、ジョブを作成し、それが作成されたことをコンソールに出力します。タイマーを 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'});
});
4

2 に答える 2

2

以下のような cron 式を作成できます。"0 0 7 8 9 ? 2020" (seconds min hour dayOfMonth Month DayofWeek Year) 、これは一度だけ実行されます。ジョブを実行する最初の日/時間に基づいて、この式を作成する必要があります。すぐに実行する必要がある場合は、現在の時刻 + 数秒のバッファーに基づいて cron 式を作成できます。

于 2020-09-07T22:39:10.067 に答える
0

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'});
});

于 2020-09-07T23:11:40.093 に答える