How to use the CronJob function from cron

Find comprehensive JavaScript cron.CronJob code examples handpicked from public code repositorys.

cron.CronJob is a constructor function that allows you to create cron jobs in your Node.js application.

202
203
204
205
206
207
208
209
210
211
    super.registerEntity(false);
}

createCronjob(crontab) {
    const node = this.node;
    this.cronjob = new CronJob({
        cronTime: crontab,
        onTick: () => {
            node.emit('input', {});
        },
fork icon57
star icon379
watch icon21

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
27
var TWILIO_SID = 'AC4d903012a56c8cba55657d6f9520846e'
var TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN
var TWILIO_NUMBER = '+19073122014'
var DELAY = 500 // throttle calls to Twilio


var job = new cron.CronJob({
    // run every day at the hour specified above
    cronTime: '0 ' + NOTIFICATION_TIME + ' * * *',
    // cronTime: '* * * * *', // every minute
    onTick: sendMessages,
fork icon6
star icon6
watch icon0

How does cron.CronJob work?

cron.CronJob is a constructor function that creates a new cron job instance with the specified schedule, a function to run when the job is triggered, and other optional configuration options such as timezone and starting the job immediately upon creation. When the job is created, it is added to a list of jobs that the cron scheduler keeps track of, and it runs the function whenever the specified schedule is triggered. The job can be stopped and restarted using the stop() and start() methods, respectively.

33
34
35
36
37
38
39
40
41
42
    if (!File.execute || !File.conf || !File.conf.event) return console.error(`[SYSTEM-MESSAGE] ${fileName} is not loaded.`);
    if (!File.conf.enabled || File.conf.enabled === false) return;
    Moderation.on(File.conf.event, File.execute);
});

const resetStats = new CronJob('00 00 00 * * 1', async function() {
  const guild = Moderation.guilds.cache.first();
  const newData = new Map();
  await Stats.updateMany({}, { Voice: newData, Message: newData });
}, null, true, 'Europe/Istanbul');
fork icon2
star icon1
watch icon1

363
364
365
366
367
368
369
370
371
372
373
374
375
376
    //use guildCommandCreate
    guildCommandCreate(guild.id);


})


let scheduledMessage = new cron.CronJob('* 15-17 * * *', async () => {


    // datedata


    let date = new Date().getDate();
fork icon0
star icon1
watch icon2

Ai Example

1
2
3
4
5
6
7
const CronJob = require("cron").CronJob;

const job = new CronJob("*/1 * * * *", function () {
  console.log("Running function every minute");
});

job.start();

In this example, a new CronJob is created with the cron expression '*/1 * * * *', which means "run every minute." The second argument to the constructor is a function that will be executed each time the job runs. Finally, the start() method is called on the job object to begin the scheduled task.

5
6
7
8
9
10
11
  const SCHEDULE_KEY = `SCHEDULE_${key.toUpperCase()}`;
  const SCHEDULE = process.env[SCHEDULE_KEY];
  if (!SCHEDULE) {
    const error = `Schedule for cronjob is undefined ("${SCHEDULE_KEY}").`;
    console.error(new Error(error));
  } else new cron.CronJob(SCHEDULE, job[key]).start();
}
fork icon0
star icon1
watch icon2

22
23
24
25
26
27
28
29
30
31
  auth: {
    user: 'xcrwolfie@gmail.com', 
    pass: 'jiefsiykivjzpran' 
  }
});
const job = new cron.CronJob({
  cronTime: '*/2 * * * *', 
  onTick: function() {
    subscribers.forEach((subscriber) => {
      const mailOptions = {
fork icon0
star icon1
watch icon0

90
91
92
93
94
95
96
97
98
99
100
101
102
	}
}


const scheduleCronJobs = async (guildId, scheduleConfig, generateFunction) => {


	const job = new CronJob(scheduleConfig.time, async function () {


		try {
			let channelIndex = getCurrentChannelIndex(guildId, scheduleConfig);
			let channelId = scheduleConfig.channels[channelIndex];
fork icon0
star icon1
watch icon0

391
392
393
394
395
396
397
398
399
400
401
     })
        .then(console.log("Backed up planlist to inconLogs"))
        .catch(console.error);
}


const scheduledMessage = new cron.CronJob('0 * * * *', () => {
    inconLogs.send("It's an even hour right now.");
    backupFiles();
    console.log("Triggered schedule message, checking time...");
    let currentTime = new Date();
fork icon0
star icon0
watch icon1

36
37
38
39
40
41
42
43
44
45
client.once("ready", async () => {
  const kr = await fetch('https://splatoon3.ink/data/locale/ko-KR.json');
  const krnames = await kr.json();
  console.log(`Online as ${client.user.tag}`);
    
  let scheduledMessage = new cron.CronJob('0 * * * *', async () => {
  // This runs every day at 10:30:00, you can do anything you want
  // Specifing your guild (server) and your channel
     const guild = client.guilds.cache.get('193203190643032064');
     const channel = guild.channels.cache.get('193203190643032064');
fork icon0
star icon0
watch icon1

147
148
149
150
151
152
153
154
155
156
 */
async initCronJob(cronTime, timeZone, runOnce) {
  this.log(`${this.getName()} - initCronjob - cronTime: ${cronTime}, timeZone: ${timeZone}, runOnce: ${runOnce}`);

  // create cronjob with cronTime and timeZone, do not start yet
  this.cronJob = new CronJob({
    cronTime,
    onTick: () => {
      this.log(`${this.getName()} - cronJob - tick at ${new Date().toISOString()}`);
      this.cronJobRunTriggers(runOnce);
fork icon0
star icon0
watch icon1

108
109
110
111
112
113
114
115
116

console.log('get prices');
await this.tickerWatcher.start();


new CronJob(`30 3 * * 1-5`, () => this.newDay(), null, true);


this.pmsAnalyzed = await require('../analysis/sep-2019/all-pm-analysis')()
fork icon0
star icon0
watch icon1

+ 27 other calls in file

10
11
12
13
14
15
16
17
18
19
const newDateObj = new Date(d.getTime() + min * 60000);
newDateObj.setSeconds(0);
const cronStr = `${newDateObj.getMinutes()} ${newDateObj.getHours()} * * 1-5`;
// log(`new cron: "${name}" happening at ${run} minutes: ${cronStr}`);

const cronJob = new CronJob(cronStr, () => {
    if (isMarketClosed()) {
        return console.log("market closed");
    }
    const logStr = `starting cron: ${name}`;
fork icon0
star icon0
watch icon1

+ 12 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20
21
const NUMBER_OF_RETRIES = 3;


let lastState = 'Idle';
let lastResult = '';


new CronJob(CRON_TIME, () => {
    generateWithRetries(NUMBER_OF_RETRIES);
}).start();


setInterval(() => {
fork icon0
star icon0
watch icon1

+ 14 other calls in file

137
138
139
140
141
142
143
144
145
146

init() {
  if (!this.opt("cron").run) return;
  let cron = Utils.cronTime(this.opt("cron"));

  this.start_job = new CronJob({
    cronTime: cron.start,
    timeZone: this.opt("timezone"),
    onTick: async () => await this.start(),
  });
fork icon0
star icon0
watch icon0

+ 3 other calls in file

1
2
3
4
5
6
7
8
9
10
11
const db = require('../../config/db');
const backupdb = require('../../config/backupdb');
const backupController = require('../backup');
const dataDbBackup = require('../../config/dataDbBackup');


const backup = new cron.CronJob({
  /* 
   * Seconds: 0-59
   * Minutes: 0-59
   * Hours: 0-23
fork icon0
star icon0
watch icon0

14
15
16
17
18
19
20
21
22
23
const bot = new telegraf_1.Telegraf("238413949:AAEr2sNKSXZELaK9tVjNdTa-9ioP2dII6k4");
bot.start((ctx) => {
    return ctx.reply("Bot is ready");
});
let newPairs = [];
const job = new cron_1.CronJob({
    cronTime: "* * * * *",
    onTick: () => __awaiter(void 0, void 0, void 0, function* () {
        let pairRes;
        console.log("Getting currency pairs");
fork icon0
star icon0
watch icon0

54
55
56
57
58
59
60
61
62
63
64
var cfgExpFilesRemovedAtOnce = config.get('expire.filesremovedatonce');
var cfgForceSaveEnable = config.get('autoAssembly.enable');
var cfgForceSaveStep = ms(config.get('autoAssembly.step'));


function getCronStep(cronTime){
  let cronJob = new cron.CronJob(cronTime, function(){});
  let dates = cronJob.nextDates(2);
  return dates[1] - dates[0];
}
let expFilesStep = getCronStep(cfgExpFilesCron);
fork icon0
star icon0
watch icon0

40
41
42
43
44
45
46
47
48
49
})
const descriptionData = getDescription(groups[0].description)
const locations = descriptionData[1]
const timeTrigger = descriptionData[0]
console.log('Before job instantiation');
job = new CronJob(`${timeTrigger} * * *`, () => {
fetchWeather({apiKey:apiKey, locations:locations}).then(data => {
    const weatherText = formatForText(cleanTomorrowForecast(data)).join("")
    const textToSend = `*🦢🤖--Ganso-bot--🤖🦢*
    *"Tomorrows weather"*
fork icon0
star icon0
watch icon0

28
29
30
31
32
33
34
35
36
37
//setInterval(() => { TagKontrol4(); }, 120 * 1000);
setInterval(() => { cezaKontrol(); }, 15 * 1000);
setInterval(() => { gorevKontrol(); }, 15* 1000)
try {
  const ramal = await Ramalcim.findOne({ guildID: config.guildID })
  const gorevs = new CronJob("00 00 * * *", () => {
    client.guilds.cache.forEach(async (guild) => {
      let arr = ["davet", "mesaj", "ses", "taglı", "teyit"];
      let dagit = []
      await client.guilds.cache.get(config.guildID).roles.cache.get(ramal.registerHammer).members.array().forEach((x, index) => {
fork icon0
star icon0
watch icon0