我在寻找nodejs的schedule / cron。但是我需要一个重要的功能 - 如果工作没有完成(当它再次开始的时候到了),我希望它不能启动/延迟时间表。为……
你可以使用 cron的 包。它允许您手动启动/停止cronjob。这意味着您可以在完成cronjob时调用这些函数。
const CronJob = require('cron').CronJob; let job; // The function you are running const someFunction = () => { job.stop(); doSomething(() => { // When you are done job.start(); }) }; // Create new cronjob job = new CronJob({ cronTime: '00 00 1 * * *', onTick: someFunction, start: false, timeZone: 'America/Los_Angeles' }); // Auto start your cronjob job.start();
您可以自己实现:
// The job has to have a method to inform about completion function myJob(input, callback) { setTimeout(callback, 10 * 60 * 1000); // It will complete in 10 minutes } // Scheduler let jobIsRunning = false; function scheduler() { // Do nothing if job is still running if (jobIsRunning) { return; } // Mark the job as running jobIsRunning = true; myJob('some input', () => { // Mark the job as completed jobIsRunning = false; }); } setInterval(scheduler, 5 * 60 * 1000); // Run scheduler every 5 minutes