10
votes

I have a cron job setup, with the minimum value of 60 seconds, and I want the program to be able to run at second intervals i.e. whatever I set it as 60 seconds onwards.

So for example, I want the cron job to run every 65 seconds, or every 63 seconds, or every 160 seconds etc.

Is this possible? Or is cron job only set to run at 60 second intervals?

If yes, what would the cron job for this look like?

I managed to make it run every 'x' minutes: So far, I have managed to use a database value which the user inserts to run the cron job every set number of minutes. Which looks like this:

  cron.schedule('*/' + test + ' * * * *', function () {
    console.log('running a task every minute');
  });

With the schema looking like:

var CronSchema = new mongoose.Schema({
  minutes: { type: Number, min: 1 }
})

How can I run a cron job every 'x' seconds? Ideally, I would only allow a user to input a value in seconds, so if they want the job to run every two minutes they would have to input 120 seconds.

2
Are you actually using cron or not? - OrangeDog
Why not use setInterval? - DrakaSAN
The Linux cron daemon only checks every minute. To run anything on a x second timer you would need to involve some other mechanism. - Klas Lindbäck
Yes I am actually using cron. The main aim is to allow the user to set how often the cron job will run. Could I do that with setInterval? And what other mechanism is needed? - deeveeABC
It looks like you're using cron middleware for Node, which generally just uses javascript timers under the hood. - adeneo

2 Answers

16
votes

If you're using middleware for Node, you can add seconds as well

cron.schedule('*/' + test + '0,30 * * * * *', function () {
    console.log('running a task every minute');
});

Will run every 30 seconds, i.e. on xx:00:000 and xx:30:000

Note that javascript versions have six values, and not five like native Linux Cron, meaning the sixth is for seconds, which would be the first one

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

Full documentation on allowed values can be found in the crontab documentation

1
votes
cron.schedule('*/' + test + '0,x * * * * *', function () {
   console.log('running a task every x seconds');
});

this will run every x seconds.