Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

node.js - Cron - Run every year once at January 1 00:00 or 12.00 am

I am using npm i cron to run cron schedule in node.js. I want to run the schedule every start of the year at 12.00 am i.e Jan 1 every year once at 12.00 am . How can I make it run? Anybody can help please.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to use the code below to do this. When the script starts, it will print out the next 10 dates the job will run on:

const CronJob = require("cron").CronJob;

const cronExpression ="0 0 1 JAN *";

const cronJob = new CronJob(
    cronExpression,
    cronFunction
);

function cronFunction() {
    console.log("cronFunction: Running....");
    // Add whatever you wish here...
}

// Print out the next dates the job will run
const nextDates = cronJob.nextDates(10);
console.log("Next dates the job will run on:", nextDates.map(d => d.format("YYYY-MM-DD HH:mm")));

cronJob.start();

The output should look like so:

Next dates the job will run on: [
  '2022-01-01 00:00',
  '2023-01-01 00:00',
  '2024-01-01 00:00',
  '2025-01-01 00:00',
  '2026-01-01 00:00',
  '2027-01-01 00:00',
  '2028-01-01 00:00',
  '2029-01-01 00:00',
  '2030-01-01 00:00',
  '2031-01-01 00:00'
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...