Giter Club home page Giter Club logo

node-cron's Introduction

cron for Node.js logo
cron is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
Perfect for tasks like data backups, notifications, and many more!

Cron for Node.js

Version Monthly Downloads Build Status CodeQL Status Coverage Renovate OpenSSF Scorecard Discord

🌟 Features

  • execute a function whenever your scheduled job triggers
  • execute a job external to the javascript process (like a system command) using child_process
  • use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
  • use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)

πŸš€ Installation

npm install cron

Table of Contents

  1. Features
  2. Installation
  3. Migrating from v2 to v3
  4. Basic Usage
  5. Cron Patterns
  6. Gotchas
  7. API
  8. Community
  9. Contributing
  10. Acknowledgements
  11. License

πŸ”„ Migrating from v2 to v3

With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made:

Migrating from v2 to v3

Month & day-of-week indexing changes

  • Month Indexing: Changed from 0-11 to 1-12. So you need to increment all numeric months by 1.

  • Day-of-Week Indexing: Support added for 7 as Sunday.

Adjustments in CronJob

  • The constructor no longer accepts an object as its first and only params. Use CronJob.from(argsObject) instead.
  • Callbacks are now called in the order they were registered.
  • nextDates(count?: number) now always returns an array (empty if no argument is provided). Use nextDate() instead for a single date.

Removed methods

  • removed job() method in favor of new CronJob(...args) / CronJob.from(argsObject)

  • removed time() method in favor of new CronTime()

πŸ›  Basic Usage

import { CronJob } from 'cron';

const job = new CronJob(
	'* * * * * *', // cronTime
	function () {
		console.log('You will see this message every second');
	}, // onTick
	null, // onComplete
	true, // start
	'America/Los_Angeles' // timeZone
);
// job.start() is optional here because of the fourth parameter set to true.
// equivalent job using the "from" static method, providing parameters as an object
const job = CronJob.from({
	cronTime: '* * * * * *',
	onTick: function () {
		console.log('You will see this message every second');
	},
	start: true,
	timeZone: 'America/Los_Angeles'
});

Note: In the first example above, the fourth parameter to CronJob() starts the job automatically. If not provided or set to falsy, you must explicitly start the job using job.start().

For more advanced examples, check the examples directory.

Cron Patterns

Cron patterns are the backbone of this library. Familiarize yourself with the syntax:

- `*` Asterisks: Any value
- `1-3,5` Ranges: Ranges and individual values
- `*/2` Steps: Every two units

Detailed patterns and explanations are available at crontab.org. The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like crontab.guru can help in constructing patterns but remember to account for the seconds field.

Supported Ranges

Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:

field          allowed values
-----          --------------
second         0-59
minute         0-59
hour           0-23
day of month   1-31
month          1-12 (or names, see below)
day of week    0-7 (0 or 7 is Sunday, or use names)

Names can also be used for the 'month' and 'day of week' fields. Use the first three letters of the particular day or month (case does not matter). Ranges and lists of names are allowed.
Examples: "mon,wed,fri", "jan-mar".

Gotchas

  • Both JS Date and Luxon DateTime objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JS Date or Luxon DateTime objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues.

  • Using arrow functions for onTick binds them to the parent's this context. As a result, they won't have access to the cronjob's this context. You can read a little more in issue #47 (comment).

API

Standalone Functions

  • sendAt: Indicates when a CronTime will execute (returns a Luxon DateTime object).

    import * as cron from 'cron';
    
    const dt = cron.sendAt('0 0 * * *');
    console.log(`The job would run at: ${dt.toISO()}`);
  • timeout: Indicates the number of milliseconds in the future at which a CronTime will execute (returns a number).

    import * as cron from 'cron';
    
    const timeout = cron.timeout('0 0 * * *');
    console.log(`The job would run in ${timeout}ms`);

CronJob Class

Constructor

constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout):

  • cronTime: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JS Date object or a Luxon DateTime object.

  • onTick: [REQUIRED] - Function to execute at the specified time. If an onComplete callback was provided, onTick will receive it as an argument.

  • onComplete: [OPTIONAL] - Invoked when the job is halted with job.stop(). It might also be triggered by onTick post its run.

  • start: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is false.

  • timeZone: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the Luxon documentation.

  • context: [OPTIONAL] - Execution context for the onTick method.

  • runOnInit: [OPTIONAL] - Instantly triggers the onTick function post initialization. Default is false.

  • utcOffset: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with timeZone.

  • unrefTimeout: [OPTIONAL] - Useful for controlling event loop behavior. More details here.

Methods

  • from (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.

  • start: Initiates the job.

  • stop: Halts the job.

  • setTime: Modifies the time for the CronJob. Parameter must be a CronTime.

  • lastDate: Provides the last execution date.

  • nextDate: Indicates the subsequent date that will activate an onTick.

  • nextDates(count): Supplies an array of upcoming dates that will initiate an onTick.

  • fireOnTick: Allows modification of the onTick calling behavior.

  • addCallback: Permits addition of onTick callbacks.

CronTime Class

Constructor

constructor(time, zone, utcOffset):

  • time: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS Date object.

  • zone: [OPTIONAL] - Equivalent to timeZone from CronJob parameters.

  • utcOffset: [OPTIONAL] - Analogous to utcOffset from CronJob parameters.

🀝 Community

Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.

🌍 Contributing

This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.

πŸ› Submitting Bugs/Issues

Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.

πŸ™ Acknowledgements

This is a community effort project. In the truest sense, this project started as an open source project from cron.js and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.

Special thanks to Hiroki Horiuchi, Lundarl Gholoi and koooge for their work on the DefinitelyTyped typings before they were imported in v2.4.0.

License

MIT

node-cron's People

Contributors

bvigursky avatar calmh avatar cliftonc avatar codersbrothers avatar danhbear avatar errolfernandes avatar gijsvandenhoven avatar humanchimp avatar immanuel192 avatar intcreator avatar jodevsa avatar joeysino avatar jordanabderrachid avatar karjaneth avatar kyleamathews avatar matheusvellone avatar mle-ii avatar ncb000gt avatar nel215 avatar nilpotence avatar nmay231 avatar padolsey avatar quadriphobs1 avatar renovate[bot] avatar rharshit82 avatar semantic-release-bot avatar sheerlox avatar shuat avatar tbantoni avatar toots avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-cron's Issues

CronTime day of week is non-standard (Sunday is 1, not 0)

The documentation referenced in the readme says that day of week is 1-7, Sunday being 1.
http://help.sap.com/saphelp_xmii120/helpdata/en/44/89a17188cc6fb5e10000000a155369/content.htm

All other crontab documentation I see says that day of the week is 0-6, Sunday being 0.
http://crontab.org/
http://en.wikipedia.org/wiki/Cron
http://www.adminschoice.com/crontab-quick-reference

Mind if I submit a patch to change? Or would you like a "compatibility mode" that explicitly requests real cron times?

I'd also like to support the standard 5-digit crontime syntax that doesn't include seconds. Mind if I submit a patch to default to "a b c d e f" to "0 a b c d e f" ?

Only execute the job if it is no longer running

I have a job that is scheduled to run every minute. On occasions this job takes more than 1 minute to complete and in this case i don't want to prevent the scheduler from executing the job again.

Is there any way to achieve this?

cheers

Testing breaks when seconds are based on current time but extend past 60 seconds.

When run this test will sometimes pass and sometimes fail. Ultimately it depends on when the test is run.

start: 59
end: 63
βœ– test every second for a range with oncomplete ([start]-[end] * * * * *)

Error: Expected 5 assertions, 1 ran
    at Object.done (/Users/ncampbell/Code/node-cron/node_modules/nodeunit/lib/types.js:121:25)
    at Object._onTimeout (/Users/ncampbell/Code/node-cron/tests/test-cron.js:98:14)
    at Timer.ontimeout (timers.js:84:39)

This is a problem because the test is calculated based on current time and expects the test to take no more than 6 seconds. I'll have to update the test such that if it will overlap the minute it will just extend the timeout and change the start and end values.

no stop() method

could we add a stop method?

,

stop: function() {
clearTimeout(this.timer);
this.events = [];
}

Timezone does not worked as expected

Hi, i have a node app which it's time set to UTC timezone with this code.

process.env.TZ = 'UTC';

and then i have a cron code like this

// Execute the job at 01:00:00 AM
new cronJob('00 00 01 * * *', function () {
    console.log('Executed cron');
}, true, 'Asia/Jakarta');

Then 01:00:00 Jakarta time, the cron does not executed.
Instead it's executed on 01:00:00 UTC time.

I believe this is not the correct behaviour?
Or did i implement it wrong?

PS. I already require('time'); module.

Thank you

What is the most appropriate way to keep the program from quitting?

I have a program like this:

var cronJob = require('cron').CronJob;
var job1 = new cronJob('0 30 23 * * *', function () {
    // do something.
}, null, false);

However, it quits immediately after creating the cron job. What is the most appropriate way in node to keep the program from quitting? Thanks.

npm registry update

According to npm registry the latest version is 0.1.3 (package cron), or 0.1.8 (package cron2), but this repo's version is 1.0.0. Do you plan to push the new version?

setTimeout(job.stop, 5000) does not stop the job

I believe this is not a problem of node-cron, but rather a question in javascript. The following code demonstrates the question. The cron job starts without any problem. However, it doesn't stop with the code setTimeout(job.stop, 5000), whereas it stops as expect with the following code:

// Stops as expected
setTimeout(function () {
    job.stop();
}, 5000);
var cronJob = require('cron').CronJob;
var job = new cronJob('* * * * * *', function () {
    console.log('You will see this message every second');
});

job.start();

// Does not stop
// setTimeout(job.stop, 5000); 

// Stops as expected
setTimeout(function () {
    job.stop();
}, 5000);

cron.search

Searching for a range of crons (gimme all crons between tomorrow and the day after).

cron.update

Allow for updating of a specific cron event...this could be onTick or a function to be fired.

Can't handle "first of every month"

A cron string that should fire at a specific time on the first day of the month instead fires multiple times each second. For example, the script:

var CronJob = require('cron').CronJob;

new CronJob('00 00 4 1 * *', function () {
    console.log('04:00:00, 1st of every month:', new Date());
}, null, true, 'UTC');

new CronJob('00 00 4 2 * *', function () {
    console.log('04:00:00, 2nd of every month:', new Date());
}, null, true, 'UTC');

gives the output:

jb@apto:~/tmp % node test.js
04:00:00, 1st of every month: Sun Jul 01 2012 16:20:53 GMT+0200 (CEST)
04:00:00, 1st of every month: Sun Jul 01 2012 16:20:53 GMT+0200 (CEST)
04:00:00, 1st of every month: Sun Jul 01 2012 16:20:53 GMT+0200 (CEST)
04:00:00, 1st of every month: Sun Jul 01 2012 16:20:54 GMT+0200 (CEST)
...etc

The test suite seems to pass, though. Node 0.8.1.

Wrong description for getTimeout

Hi, thank you for this great library!

I had trouble finding out how long it will take until the next run, so I dug through the code and the description for getTimeout of CronTime unfortunately misguided me.

/**
    * Get the number of seconds in the future at which to fire our callbacks.
*/

This is wrong as it actually are milliseconds(from Date.getTime). Would be nice if you could fix this, or would you rather see a pull request?

Memory leak

Hi, I'm facing a big issue !!

My cron job retrieve some data with, each time, a different URL and I have this warning message

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
    at Socket.EventEmitter.addListener (events.js:176:15)
    at ClientRequest.createRequest (/var/www/manager.pinchproject.com/admin/api/node_modules/shred/lib/shred/request.js:400:25)
    at ClientRequest.EventEmitter.emit (events.js:123:20)
    at ClientRequest.onSocket (http.js:1524:9)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

How can I change the number of listeners ?

Thank you.

The usage example doesn't work in the readme file.

In my environment, the following usage described in the readme file outputs the error message.

Code

var cronJob = require('cron');
cronJob('* * * * * *', function(){
    console.log('You will see this message every second');
});

Error Message

_node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object # has no method 'cronJob'
at Object. (/Users/xxx/xxxx.js:361:6)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at Array. (module.js:421:10)
at EventEmitter.tickCallback (node.js:126:26)

The following code works properly:

Code

var cronJob = require('cron');
cron.CronJob('* * * * * *', function(){
    console.log('You will see this message every second');
});

Anyway, thank you for great node module!

onComplete not being called

I set up a very simple test program to run a few times and then used setTimeout to stop the job. However my onComplete function never seems to be called, the job is stopping though.

var cronJob = require('cron').CronJob

function cronRun() { console.log('run'); }
function cronStopped() { console.log('stopped'); }
function stopCronJob(j) { j.stop(); }

job = new cronJob('*/15 * * * * *', cronRun, cronStopped, true);
setTimeout(stopCronJob, 35000, job);

Change CronTime after job is created

I'm trying to find out if there's a way to change the CronTime of a job after the job is created..

I have tried using the CronTime object, but it does not seem to respect it's own prototype as it does not find the parse method:

What I have tried :

job.cronTime = require('cron').CronTime("0 10 * * *","America/Montreal");

but when I try that I get

TypeError: Object # has no method '_parse' at Object.CronTime (cron.js:24:10)

Functions will be executed immediately

I set my cronjob as follows

var cronJob = require('cron').CronJob;

try {
new cronJob({
cronTime: '00 '+min+' '+hour+' * * '+days,
onTick:
console.log('00 '+min+' '+hour+' * * '+days),
start: true
});
} catch(ex) {
console.log("Cron pattern not valid");
}

but the function in onTick is executed immediately and not at the specific cronTime. What am I doing wrong?

Cron job loops 60 times

Each time I run my script, the job iterates 60 times. What am I doing wrong?

// ####### The Code #######
var cronJob = require('cron').CronJob;
var time = require('time');

var iterate = 0; // Let's keep track of how many times the job runs!

function theJob() {
console.log('Iterate Loop: '+iterate); // Output the iteration
iterate = iterate + 1; // increment the iteration.
}

new cronJob('* */2 * * * *', theJob, null, false, "UTC");

job.start();
// ####### End Code #######

// ####### The Output #######
project:~ escadmin$ node /www_root/scripts/test.js
Iterate Loop: 0
Iterate Loop: 1
Iterate Loop: 2
Iterate Loop: 3
Iterate Loop: 4
Iterate Loop: 5
Iterate Loop: 6
Iterate Loop: 7
Iterate Loop: 8
Iterate Loop: 9
Iterate Loop: 10
Iterate Loop: 11
Iterate Loop: 12
Iterate Loop: 13
Iterate Loop: 14
Iterate Loop: 15
Iterate Loop: 16
Iterate Loop: 17
Iterate Loop: 18
Iterate Loop: 19
Iterate Loop: 20
Iterate Loop: 21
Iterate Loop: 22
Iterate Loop: 23
Iterate Loop: 24
Iterate Loop: 25
Iterate Loop: 26
Iterate Loop: 27
Iterate Loop: 28
Iterate Loop: 29
Iterate Loop: 30
Iterate Loop: 31
Iterate Loop: 32
Iterate Loop: 33
Iterate Loop: 34
Iterate Loop: 35
Iterate Loop: 36
Iterate Loop: 37
Iterate Loop: 38
Iterate Loop: 39
Iterate Loop: 40
Iterate Loop: 41
Iterate Loop: 42
Iterate Loop: 43
Iterate Loop: 44
Iterate Loop: 45
Iterate Loop: 46
Iterate Loop: 47
Iterate Loop: 48
Iterate Loop: 49
Iterate Loop: 50
Iterate Loop: 51
Iterate Loop: 52
Iterate Loop: 53
Iterate Loop: 54
Iterate Loop: 55
Iterate Loop: 56
Iterate Loop: 57
Iterate Loop: 58
Iterate Loop: 59

// ####### End Output #######

Any thoughts? I'm running Node v0.10.25, cron 1.0.3, and time 0.10.0. I've stripped it down to the simplest example, and it still loops. HELP!

Explicit start to cron jobs.

Cron jobs should be explicitly started with cron.start(). This will allow for a few other setup things to happen before a cron starts actually firing.

Automated tests.

test.js is only a visual indicator that something happened. That is not testing.

Need to have real tests for this.

Manually Stop The Cron Job

I have one condition check before executing cron job.

i wrote the code here::

function check mail()
{

var job = new cronJob('*/3 * * * * *', function() {
console.log("This is test Message Started");
}, null, false, "America/Los_Angeles");

if(req.param('emaiibtn')=='true')
{
console.log("true");
job.start();
}
else
{
console.log("false");
setTimeout(function() {
job.stop();
}, 10000);

}
}

whenever the condition is false, stop fn executed, but immediately start fn also executed. so cron job is still running.
Any body have solution...

Calling cronJob with native Date will fire 1s too late

If you pass a native Date object to a new cronJob, the job will fire exactly one second to late.
For example: new Date("7 August 2012 14:50:00 UTC") will cause the job to run at 14:50:01 UTC.

Here’s how to reproduce it:

var cronJob = require('cron').CronJob;
new cronJob(new Date("7 August 2012 14:50:00 UTC"), function() {
  now = new Date();
  console.log(now.getSeconds(), now.getMilliseconds());
}, null, true);

CronTime.sendAt does not always return the first eligible date

The sendAt logic basically increments each date unit (starting with month, ending with seconds) until a match is hit. Depending on the value of the current date and the crontab, this might not always yield the desired result.

For example, take the crontime string "00 00 17 * * *" to trigger at 5pm daily. At the time of writing, that should return Tuesday 5pm, but instead returns Wednesday 5pm. You can ensure this repros by setting var date = new Date(2012, 3, 16, 22, 45, 30); instead of new Date() in the first line of the function.

I have a quick change that handles the above case (excessive roll-over in seconds/minutes/hours), but am thinking if theres an approach that avoids this for days/months. Will hopefully send a pull request tomorrow if that's cool.

Loop output from example described above:

Mon Apr 16 2012 22:45:31 GMT-0700 (PDT)
Mon Apr 16 2012 23:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 00:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 01:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 02:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 03:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 04:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 05:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 06:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 07:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 08:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 09:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 10:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 11:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 12:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 13:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 14:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 15:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 16:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:31 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:32 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:33 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:34 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:35 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:36 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:37 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:38 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:39 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:40 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:41 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:42 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:43 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:44 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:45 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:46 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:47 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:48 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:49 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:50 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:51 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:52 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:53 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:54 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:55 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:56 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:57 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:58 GMT-0700 (PDT)
Tue Apr 17 2012 17:00:59 GMT-0700 (PDT)
Tue Apr 17 2012 17:01:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:02:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:03:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:04:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:05:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:06:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:07:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:08:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:09:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:10:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:11:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:12:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:13:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:14:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:15:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:16:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:17:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:18:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:19:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:20:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:21:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:22:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:23:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:24:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:25:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:26:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:27:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:28:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:29:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:30:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:31:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:32:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:33:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:34:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:35:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:36:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:37:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:38:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:39:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:40:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:41:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:42:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:43:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:44:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:45:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:46:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:47:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:48:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:49:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:50:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:51:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:52:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:53:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:54:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:55:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:56:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:57:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:58:00 GMT-0700 (PDT)
Tue Apr 17 2012 17:59:00 GMT-0700 (PDT)
Tue Apr 17 2012 18:00:00 GMT-0700 (PDT)
Tue Apr 17 2012 19:00:00 GMT-0700 (PDT)
Tue Apr 17 2012 20:00:00 GMT-0700 (PDT)
Tue Apr 17 2012 21:00:00 GMT-0700 (PDT)
Tue Apr 17 2012 22:00:00 GMT-0700 (PDT)
Tue Apr 17 2012 23:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 00:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 01:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 02:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 03:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 04:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 05:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 06:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 07:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 08:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 09:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 10:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 11:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 12:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 13:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 14:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 15:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 16:00:00 GMT-0700 (PDT)
Wed Apr 18 2012 17:00:00 GMT-0700 (PDT)

My cron does not start!

Nothing happens...
new CronJob('0 0 * * * *', function() {console.log('WTF')}).start();

ΒΏ?

Allow sintax like whenever (ruby gem)

For most people will be much easier to use something like (this its ruby sintax but can be implemented in js i think)

every 3.hours do
  runner "MyModel.some_process"       
  rake "my:rake:task"                 
  command "/usr/bin/my_great_command"
end

every 1.day, :at => '4:30 am' do 
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  runner "SomeModel.ladeeda"
end

every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday 
  runner "Task.do_something_great"
end

every '0 0 27-31 * *' do
  command "echo 'you can use raw cron syntax too'"
end

https://github.com/javan/whenever

JSON Parse Unexpected End of Input

I have a chained group of HTTP requests I wrap in a cron call to run every three hours. The chained function works fine if I call it independently but crashes with an "Unexpected end of input" error after a few calls via the cron module. The error shows that the JSON output from the HTTP requests is being clipped mid-stream.

I removed some console.log commands and it seemed to run for a few more iterations than when I had more logs being called. Is the cron running out of memory or something? Thanks.

cron.add/remove

Allow for addition and removal of events to a single cron task at a specific time.

Drowning...

Actually this is not a question I think but more a remark. I was curious what kind of behavior to except when I drown node-cron in to much work. I created a job with an interval of 1 second and in the job I incremented an int via redis (loop with 100k increments).

I measured that on my computer every three seconds the cron job actually starts (and finishes). So I think (this is a question ;-) ) node-cron drops job requests when it is to busy (which is off-course fine and totally OK).

Am I right?

Cron jobs kicked off at wrong time for Daylight Savings Time

Sunday morning the Cron job that we had set up to go off at 9am and 9pm every day decided to start kicking off jobs at 1 am local time. It ran as many times as it could from 09:00 to 09:01 UTC. This job had worked flawlessly up until that day.

The times are Pacific time. So they were 17:00 UTC and 05:00 UTC. And on Sunday morning they kicked off at 09:00 UTC. So perhaps node-cron got confused about the timezone? Or I should have set the timezone specifically or used UTC instead.

Here's the code that sets it up:

var job = new cronJob({
  cronTime: '00 00 09,21 * * *',
  onTick: function() {
    logMessage('cron job running');
    // Runs every weekday at 9:00 AM and 9:00 PM
    runPerformanceTests();
  },
  start: true
});

Create only one cron

Hello!

I'm using this peace of code in my controller:

new cronJob('*/15 * * * * *', function(){
console.log("One cron running every 15s");
}, null, true);

If I refresh the page, the Controller will create another cron, and I will have 2 running.
Its possible to create only one with a if( ) for example:

if(!cron.exist){ CREATE CRON }else{ NOTHING }

Thanks!!! ;)

Generating CronJobs in a for loop! the last onTick is applied!

I am trying to generate a few CronJobs by using the for loop!
I tried every other method but it seems like that the last member of my loop overwrites other onTick functions. This would never happen if I create new CronJobs out of the loop.

function getRequest(  ){
    for( category in data.urlCategories ){

        var option = data.baseOption; 
        option.path = data.urlCategories[category].path;   
        var sampling = data.urlCategories[category].cronSampling + data.baseCronSampling;

        new ( require('cron').CronJob)( 
            sampling , 
            function(){
                console.log('Crone Job: ' + option.path + ' with this Sampling ' + sampling );
            }
            , null, true, null);
    }  

I tried so many flavors of making a new CronJob but it always overwrites!

A better way to create new CronJob

I'm using node-cron with CoffeeScript and I have difficult using it.

This is the code how I create new CronJob

daily = new CronJob
  cromTime: '00 00 00 * * *'
  onTick: ->
    cronTask('daily')
  start: false

I follow the sample code in the README.md. https://github.com/ncb000gt/node-cron#for-good-measure ,And I think my code should be fine, but it's not actually working. It will pops up error like this:

    source = this.source.replace(/[a-z]{1,3}/ig, function(alias){
                         ^
TypeError: Cannot call method 'replace' of undefined
    at Object.CronTime._parse (/.../node_modules/cron/lib/cron.js:173:26)

I have no idea what happen, so I look into the code of node-cron. It's seems I cannot pass a JSON object for creating new CronJob Object. I'm not sure if this was the problem, But It should need to change. This is the code from connect-redis which I think is a better way to create new object:

 function RedisStore(options) {
    ...
    options = options || {};
    Store.call(this, options);
    this.prefix = null == options.prefix
      ? 'sess:'
      : options.prefix;

    this.client = options.client || new redis.createClient(options.port || options.socket, options.host, options);
    if (options.pass) {
      ...   
    }

    this.ttl =  options.ttl;
    ...
  };

There are many options to create a CronJob while only two attributes is required. And the current way to create a CronJob will make the code written in CofeeScript become really messy.

I hope you can consider changing it. Thank you.

cron job with date never stops

This code will wait 3 seconds and then print "run" every second

var d = new Date().getTime() + 3000;                                                                                                                                                                                                                                      
var job = cron.job(new Date(d), function() {                                                                                                                                                                                                                              
  console.log('run');                                                                                                                                                                                                                                                     
});                                                                                                                                                                                                                                                                       
job.start();

Issue appears to be here:

//add 1 second so next time isn't now (can cause timeout to be 0)                                                                                                                                                                                                   
date.setSeconds(date.getSeconds() + 1);          

If I remove this line, it fixes it. What was the use case where you would need to add a second?

Start/Stop not working ?

'start': true /* Start the job right now */ argument doesn't work for me, no matter what i try

Also, once the job has started, calling a stop() doesn't stop it

Jobs backup in case of server failure/app crash.

As we all know, failures happen. And once that happens, all scheduled jobs are lost permanently. Wouldn't it be reasonable to add an option (at least one) for users to backup those jobs somehow or should that rather be handled on per user basis?
related example

API might look like that:

var cronJob = require('cron').CronJob;
cronJob.backup(true, 'jobs'); // (Boolean enable [, String collection] ) - for all newly created jobs
var job = new cronJob({
  cronTime: '00 30 11 * * 1-5',
  onTick: function() {
    // Runs every weekday (Monday through Friday)
    // at 11:30:00 AM. It does not run on Saturday
    // or Sunday.
  },
  start: false,
  timeZone: "America/Los_Angeles"
});
job.backup('jobs'); // ([String collection]) - overrides/sets collection to be used for that one job
job.start();

I can do that, I just want your insights/suggestions first.

Memory leak on heroku

Hello,

I'm having a hard time with my app hosted on a single free dyno on heroku.

After a day o so I get the following error on the Heroku logs:

Error R14 (Memory quota exceeded)
Process running mem=520M(101.7%)

Until it finally crashes.

My app has 3 crons. 1 runs once a month, 1 once a day and another that runs every 30 seconds. I'm guessing the problem should be on the last one, my code for said cronjob looks a little like:

var y = null;
new cronJob('*/30 * * * * *', function (){
    request.get(url, function(err, response, body) {
            var x = JSON.parse(response).data;
            if(x.length > 0){
                if(!y) y = new Date(x[0].createdAt)
                else{
                    var z = null;
                    for(var i=0; i < x.length; i++){
                        var p = new Date(x[i].createdAt);
                        if(p > y){ 
                            //it never passed here when the leak happened
                            ...
                        }else  break;
                    }
                }
            }
        }
    });

}, null, true, null);

I've started using Nodetime to determine where's the leak but I honestly don't understand the memory profiler output, here it's part of it in case it helps:

Retainers
    87% - Other
        Size (KB): 28856.977
        Size (%): 87
        Count: 30601
        Count (%): 43
        Largest instances
            native object: Buffer
            native object: Buffer
            native object: Buffer
            array: (object properties)
            array: (object properties)
            array
            string: (function (exports, requi...
            string: (function (exports, requi...
            array: (object properties)
            array: (object properties)
        Random instances
            ...
    8% - Hidden links
        Size (KB): 2746.141
        Size (%): 8
        Count: 24476
        Count (%): 34
        Largest instances
            array
            compiled code
            compiled code
            compiled code
            compiled code
            compiled code
            compiled code
            compiled code
            array
            compiled code
        Random instances
            ...
    2% - Array elements
        Size (KB): 780.516
        Size (%): 2
        Count: 3660
        Count (%): 5
        Largest instances
            array
            compiled code
            compiled code
            compiled code
            compiled code
            compiled code: (code)
            compiled code: (code)
            compiled code
            compiled code
            compiled code: (code)
        Random instances
            ...
    0% - Property: body
    0% - Property: _label
    0% - Property: Size (KB)
    0% - Weak references
    0% - Property: prototype
    0% - Property: readme
    0% - Property: _readableState
    0% - Property: children
    0% - Property: paths
    0% - Property: exports
    0% - Variable: orig
    0% - Property: Name
    0% - Property: _writableState
    0% - Variable: func
    0% - Property: source
    0% - Variable: hook
    0% - Property: constructor
    0% - Property: id
    0% - Variable: hookBefore
    0% - Property: write
    0% - Variable: fn
    0% - Property: buffer
Objects
    65% - Buffer
        Size (KB): 21536.867
        Size (%): 65
        Count: 27
        Count (%): 0
        Largest instances
            native object: Buffer
            native object: Buffer
            native object: Buffer
            native object: Buffer
            native object: Buffer
            native object: Buffer
            native object: Buffer
            object: Buffer
            object: Buffer
            object: Buffer
        Random instances
            ...
    15% - Array
        Size (KB): 4800.617
        Size (%): 15
        Count: 16693
        Count (%): 23
        Largest instances
            array
            array: (object properties)
            array: (object properties)
            array
            array: (object properties)
            array: (object properties)
            array: (object properties)
            array: (object properties)
            array: (object properties)
            array: (object properties)
        Random instances
            ...
    9% - String
        Size (KB): 2969.656
        Size (%): 9
        Count: 26665
        Count (%): 38
        Largest instances
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
            string: (function (exports, requi...
        Random instances
            ...
    8% - compiled code
        Size (KB): 2700.922
        Size (%): 8
        Count: 8422
        Count (%): 12
        Largest instances
            compiled code
            compiled code
            compiled code
            compiled code: (code)
            compiled code
            compiled code
            compiled code
            compiled code
            compiled code: (code)
            compiled code
        Random instances
            ...
    2% - other
        Size (KB): 516.445
        Size (%): 2
        Count: 10914
        Count (%): 15
        Largest instances
            hidden: system / NativeContext
            hidden: system / NativeContext
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
            hidden: system / Context
        Random instances
            ...
    1% - Function
    0% - Object
    0% - Module
    0% - Metric
    0% - RegExp
    0% - ReadableState
    0% - WritableState
    0% - Number
    0% - Socket
    0% - NativeModule
    0% - IncomingMessage
    0% - SecurePair
    0% - Timeout
    0% - Error
    0% - CallMetrics
    0% - EncryptedStream
    0% - CleartextStream
    0% - CallMetricsGroups
    0% - Agent
    0% - Time 

Timezone support

It would be really nice if the user could set a custom timezone to run the events. :)

…
clock: function() {
    var date = new Date(custom || null);
    now = this.now,
    self = this,
…

timeout specified exceeds max warning

job = new require('cron').CronJob
  cronTime: "00 30 11 4 * *"
  onTick: () ->
    console.log "it's ll:30am on the 4th of the month"
job.start()

output:

WARNING: timeout specified (2512527997) was greater than the max of 2147483647.

Is there a way to suppress this warning? Is it even necessary? We reload our node-cron crontab on an interval and this is starting to spam our logs a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.