Giter Site home page Giter Site logo

node-cron's Introduction

Node Cron

npm npm Coverage Status Code Climate Build Status Dependency Status devDependency Status Backers on Open Collective Sponsors on Open Collective

The node-cron module is tiny task scheduler in pure JavaScript for node.js based on GNU crontab. This module allows you to schedule task in node.js using full crontab syntax.

Need a job scheduler with support for worker threads and cron syntax? Try out the Bree job scheduler!

NPM

Getting Started

Install node-cron using npm:

npm install --save node-cron

Import node-cron and schedule a task:

  • commonjs
const cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});
  • es6 (module)
import cron from 'node-cron';

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});

Cron Syntax

This is a quick reference to cron syntax and also shows the options supported by node-cron.

Allowed fields

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

Allowed values

field value
second 0-59
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names)
day of week 0-7 (or names, 0 or 7 are sunday)

Using multiples values

You may use multiples values separated by comma:

import cron from 'node-cron';

cron.schedule('1,2,4,5 * * * *', () => {
  console.log('running every minute 1, 2, 4 and 5');
});

Using ranges

You may also define a range of values:

import cron from 'node-cron';

cron.schedule('1-5 * * * *', () => {
  console.log('running every minute to 1 from 5');
});

Using step values

Step values can be used in conjunction with ranges, following a range with '/' and a number. e.g: 1-10/2 that is the same as 2,4,6,8,10. Steps are also permitted after an asterisk, so if you want to say “every two minutes”, just use */2.

import cron from 'node-cron';

cron.schedule('*/2 * * * *', () => {
  console.log('running a task every two minutes');
});

Using names

For month and week day you also may use names or short names. e.g:

import cron from 'node-cron';

cron.schedule('* * * January,September Sunday', () => {
  console.log('running on Sundays of January and September');
});

Or with short names:

import cron from 'node-cron';

cron.schedule('* * * Jan,Sep Sun', () => {
  console.log('running on Sundays of January and September');
});

Cron methods

Schedule

Schedules given task to be executed whenever the cron expression ticks.

Arguments:

  • expression string: Cron expression
  • function Function: Task to be executed
  • options Object: Optional configuration for job scheduling.

Options

  • scheduled: A boolean to set if the created task is scheduled. Default true;
  • recoverMissedExecutions: A boolean to set if the created task should be able to recover missed executions. Default false;
  • timezone: The timezone that is used for job scheduling. See IANA time zone database for valid values, such as Asia/Shanghai, Asia/Kolkata, America/Sao_Paulo.

Example:

 import cron from 'node-cron';

 cron.schedule('0 1 * * *', () => {
   console.log('Running a job at 01:00 at America/Sao_Paulo timezone');
 }, {
   scheduled: true,
   timezone: "America/Sao_Paulo"
 });

ScheduledTask methods

Start

Starts the scheduled task.

import cron from 'node-cron';

const task = cron.schedule('* * * * *', () =>  {
  console.log('stopped task');
}, {
  scheduled: false
});

task.start();

Stop

The task won't be executed unless re-started.

import cron from 'node-cron';

const task = cron.schedule('* * * * *', () =>  {
  console.log('will execute every minute until stopped');
});

task.stop();

Validate

Validate that the given string is a valid cron expression.

import cron from 'node-cron';

const valid = cron.validate('59 * * * *');
const invalid = cron.validate('60 * * * *');

Naming tasks

You can name your tasks to make it easier to identify them in the logs.

import cron from 'node-cron';

const task = cron.schedule('* * * * *', () =>  {
  console.log('will execute every minute until stopped');
}, {
  name: 'my-task'
});

List tasks

You can list all the tasks that are currently running.

import cron from 'node-cron';

const tasks = cron.getTasks();

for (let [key, value] of tasks.entries()) {
  console.log("key", key)
  console.log("value", value)
}

value is an object with the following properties:

  • _events
  • _eventsCount
  • _maxListeners
  • options
  • _task
  • etc...

Issues

Feel free to submit issues and enhancement requests here.

Contributing

In general, we follow the "fork-and-pull" Git workflow.

  • Fork the repo on GitHub;
  • Commit changes to a branch in your fork;
  • Pull request "upstream" with your changes;

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

Please do not contribute code you did not write yourself, unless you are certain you have the legal ability to do so. Also ensure all contributed code can be distributed under the ISC License.

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

node-cron is under ISC License.

node-cron's People

Contributors

bchelli avatar caarlos0 avatar chidiwilliams avatar chriseff avatar cmd430 avatar conradkirschner avatar cpena avatar dbarczewski avatar dependabot[bot] avatar dlwebdev avatar flopal avatar freedomben avatar gokulchandra avatar juneezee avatar linder3hs avatar merencia avatar monkeywithacupcake avatar muhammadtalhas avatar negezor avatar niftylettuce avatar rawatnaresh avatar recuencojones avatar root3287 avatar t-bonatti avatar theusmoreira avatar tlhunter avatar umarhussain15 avatar voltrexkeyva avatar waldyrious avatar zimgil 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

node-cron's Issues

I found that the task will not startup on time if the previous task didn't finished.

I create a con job as follows.

`
var cron = require("node-cron");
var sleep = require('sleep');
var test = 1;

function start() {
cron.schedule("* * * * * *", function () {
console.log("started");
sleep.sleep(10);
test = test + 1;
console.log(test);
console.log("finished...");
});
}

module.exports = start();
`

The output is

node src/start started 2 finished... started 3 finished... started 4 finished... started 5 finished... started 6 finished... started 7 finished... started ^C

The cron job should startup per seconds on time no matter the previous job is finished or not, right?

`immediateStart` doesn't actually start the cron job.

When immediateStart !== false, the module will execute task.update(new Date()) source. But the update function first checks if the time has come to execute the task. However, the time hasn't come because cron job is schedule to be run, say, at midnight.

The immediateStart functionality should actually execute the task immediately, not check immediately if the time has come. The current functionality just starts the timer of the cron job. I think this should be documented properly or be changed.

Run script every 13 days

Hi. Is it possible to run script every 13 days?
If I use pattern like "0 0 */13 * *" then script works

2017-06-01 00:00:00
2017-05-14 00:00:00
2017-05-27 00:00:00
2017-06-01 00:00:00
2017-06-14 00:00:00
2017-06-27 00:00:00
...

But I need:

2017-06-01 00:00:00
2017-05-14 00:00:00
2017-05-27 00:00:00
2017-06-10 00:00:00
2017-06-23 00:00:00
2017-06-05 00:00:00
...

Thank you.

Node-cron does not work with mysql database

I have a loop for my database table and for every record I want to run the cron, according to interval that specified in my database. However cron works for the last record in my table.

can i get time value in scheduled function?

hello,
i wanna know the value of time when scheduled function called.

example, i set cron job with (* * * * * *) scheduling expression,
maybe function is called every second, but i log new Date()'s second value in function at first line, this value is shown as 1, 2, 3, 4, 6, 6, 7, ...
can i get exact time when job excuted in job function?

Run a task every day at 8am

Would I only need to do the following to run a task every day (including weekdays) at 8am:

cron.schedule('0 8 * * *', function() {
  // run task
});

Correct? Or would I do:

cron.schedule('0 8 * * 0-7', function() {
});

0-7 for Monday to Sunday.

I got an error saying that "Monday to Sunday" isn't valid. So I used 0-7 instead.

screen shot 2017-03-08 at 3 15 29 pm

Job doesn't run Linux/Centos Forked Process

I've got a job set to run daily at 9am. (0 0 9 * * *)

I have a fairly large application that spawns multiple processes. This is meant to be a daily summary report. It runs fine on my dev machine (windows) but doesn't run at all on Centos.

I'm going to do some more digging but I'm wondering if this is a known thing or not?

Cron ran many times between 12am and 2am

I have a cron job that I want to run every day at 4am. I thought I had the proper cron string for that, however it ran roughly 7200+ times.

I have the following code in nodejs app.

var cron = new CronJob('* * 4 * * *', function(){
            console.log('Executing Cron: mongoDBCleanUp');
            var worker = require('./workers/mongoDBCleanUp');
            worker.execute();
        }, null, true, "America/New_York", null, false);

This is part of my logging via Papertrail.

Nov 01 01:59:53 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:53 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:54.170Z"}} 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:54.170Z"}} 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  Clean up complete 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:54 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:55.073Z"}} 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:55.073Z"}} 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  Clean up complete 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:55 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:56.262Z"}} 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:56.262Z"}} 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  Clean up complete 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:56 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:57.148Z"}} 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:57.148Z"}} 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  Clean up complete 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:57 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:58.200Z"}} 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:58.200Z"}} 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  Clean up complete 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  Executing Cron: mongoDBCleanUp 
Nov 01 01:59:58 pmx-scheduler app/worker.1:  mongodb clean up running 
Nov 01 01:59:59 pmx-scheduler app/worker.1:  ready! 
Nov 01 01:59:59 pmx-scheduler app/worker.1:  Clean up for collection: uploads with query: {"uploadDate":{"$lte":"2016-10-31T08:59:59.115Z"}} 
Nov 01 01:59:59 pmx-scheduler app/worker.1:  Clean up for collection: exports with query: {"uploadDate":{"$lte":"2016-10-31T08:59:59.115Z"}} 
Nov 01 01:59:59 pmx-scheduler app/worker.1:  Clean up complete 

Didn't working on my server

Hi,

So I tried in my local machine everythings works fine.
Then I try to run my code in the server, it didn't works. It should print running a task at 13 AM everyday at 13 AM but my code do nothing at 13 AM. Am I missing something?

my code:

var http = require('http');
var port = process.env.PORT || 9090;

var cron = require('node-cron');

cron.schedule('* 00 13 * *', function(){
  console.log('running a task at 13 AM');
});


var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");

}).listen(port);

console.log("Node server listening on port " + port);

No stop task handler for cron jobs

I would like to be able to stop my cron tasks programmatically aside from killing the whole task itself.

For that purpose, #5 has been created.

Regards.

Node-Cron with Mongodb lagging client.

I have quite regular cron jobs that pull an external API and update a mongodb database but whenever the cron jobs run, my REST API becomes unusable on the client side.

Do you have any recommendations? I have tried using mongodb pool of 10 which didnt seem to make a difference.

don't run cron if already running

is there any inbuilt function to only run the next tick if there is no other tick of the cronjob running still? In case i have a cronjob running every few seconds but sometimes it might finish slower then normal.

Multi-instance and forgotten task

hello,
i want to create x ScheduledTask with different expression and for the fast task (* * * * *) no problem but for (5 0 * * *) The task is not always executed i don't have any error juste no run :(
(it's not always the case)

it's maybe a gb problem ?

Range for hour throws error

Is setting a range not possible for the hour component of the expression? When I set a 0 8-20 * * 1-5 I get 8-20 is a invalid expression for hour as an error.

How to set timezone.

I want to know how to set the timezone for node-cron. My local node server it's working fine, Is it I have to set the timezone for the production server? How to set for different regions.
Thanks in advance.

"Every 6 hours" task firing every second?

I've been using node-cron for the last week with - so I thought - no issues. I'm using it to access an API and update a database table every 6 hours, i.e.:

var cron = require('node-cron');
cron.schedule('* * */6 * * *', rates.update);

On my development PC, I never saw an issue - tested it on my server (hosted on DigitalOcean) and all was well, so I left it running. But then I discovered that I'd been querying the API roughly 14,000 times each day... it turns out the scheduled task was randomly deciding to start firing about once a second, not once every 6 hours. And I can't for the life of me figure out why that would be, or how to force it to happen so I can pin it down!

I've tried creating test code that throws exceptions in the scheduled function, I've tried artificially adding delays into it in an attempt to simulate a time-consuming database update, but nothing has revealed a problem. Any suggestions would be gratefully received!

Pattern Interpreter handling step values.

The pattern interpreter translate expressions like this * 1-5 * Set,Oct * to * 1,2,3,4,5, * 9,10 * but it cannot interprete expressions with steps, like this '*/10 * * * *'.

So the interpreter must convert:

  • */10 * * * * to 10,20,30,40,50 * * * *
  • 1-5/2 * * * * * to 2,4 * * * *
  • 1,2,3,6,7,8/2 * * * * to 2,6,8 * * * *

After that this code and this can be removed from Task.

Cron runs multiple times at the same time

This is my code:

cron.schedule("* * 11 * * *", function () {
    logger.info("[reminderCron][cron.schedule] cron running");
    return new Promise((resolve, reject) => {
        let reminderUrl = process.env.REMINDER_URL;
        logger.info(`[reminderCron][cron.schedule] reminderUrl ${reminderUrl}`);
        let options = {
            method: "GET",
            uri: reminderUrl,
            resolveWithFullResponse: true,
            headers: {
                "content-type": "application/json"
            }
        };
        logger.info(`[reminderCron][cron.schedule] options for request ${JSON.stringify(options)}`);
        request(options)
        .then((response) => {
            logger.info("[reminderCron][doRequest] got response");
            logger.info(`[reminderCron][doRequest] ${JSON.parse(response.body)}`);
            return resolve(response);
        }).catch((err) => {
            logger.error(`[reminderCron][CatchError] error while sending reminder ${err}`);
        });
    });
});

Now this request goes multiple times at 11.

Is there some issue with my code here? Or I am assuming the cron.schedule keeps running until the time is 11:01.

Add validation on .generate Function

I was passing wrong properties to function, the function should allow object, instead of string, followed by function..

function validate(pattern){
    var patterns = pattern.split(' '); //This throws error 
    var executablePattern = convertExpression(pattern);
    var executablePatterns = executablePattern.split(' ');
    ...

It can be fixed with validation before we use pattern variable..
We can do this:

function validate(pattern){
    if (pattern.constructor != String) { 
        throw new Error("pattern should be string.") 
    }
    var patterns = pattern.split(' '); //This throws error 
    var executablePattern = convertExpression(pattern);
    var executablePatterns = executablePattern.split(' ');
    ...

Error when I get the pattern from an Object wihtin an array foreach

When I try to get the time pattern from an Object within an foreach(Array) I get this error:

node_modules\node-cron\src\convert-expression\month-names-conversion.js:10
expression = expression.replace(new RegExp(items[i], 'gi'), parseInt(i, 10) + 1);
^

TypeError: Cannot read property 'replace' of undefined
at convertMonthName (node_modules\node-cron\src\convert-expression\month-names-conversion.js:10:30)
at interprete (node_modules\node-cron\src\convert-expression\month-names-conversion.js:16:23)
at interprete (node_modules\node-cron\src\convert-expression\index.js:38:22)
at validate (node_modules\node-cron\src\pattern-validation.js:45:29)
at new Task (node_modules\node-cron\src\task.js:27:5)
at Object.createTask [as schedule] (node-cron\src\node-cron.js:18:16)
at index.js:59:22
at Array.forEach (native)
at index.js:55:18
at index.js:114:3

Cronjobs automatically stop after a certain amount of time

I'm using your module and I noticed that after a certain amount of time (has no fixed amount), the module stops working.

log

The cronjob runs, executes, this process repeats a few times and then out of nowhere, it just seems to stop working. I'm not sure if this has anything to do with a Node issue (like setInterval being bugged) or that it has to do with your module, but I find it strange that this keeps happening.

I can't seem to find out how to debug this, so hopefully anyone else can give me some insight into why this happens and how I can solve it.

I'm using Node version 5.10.1.

Runing cron every day of week ( monday to friday) at 9:00 am (GMT)

Hello could you help please , i didnt understand how to write cron job , i need to run a task every day of work week ( monday to friday) at 9:00 am (morning ) GMT (London Time Zone)

Thank you very much in advance

( I am sorry i forgot to add this as question because its not an issue)

Able to select timezone

I'm actually working in a project which involves scheduling distributed devices to turn them ON or OFF (example: turn off every midnight). The thing is that the time depends on user's timezone, and the server is set to UTC time, so I can't hardcode the scheduling to be '0 0 * * *', because this refers to 12 AM in UTC.

It would be nice to add another argument in the schedule method to specify the timezone, and manages all the UTC offset issues, including the daylight saving time changes.

There's this other node-cron library which implements it, but I had loads of issues with it, so that's why I migrated to this library. The only thing that I miss is this feature.

Node-cron sometimes misses execution when seconds are specified

The check interval fore something to run is 1000 ms. Thats why you sometimes miss an execution if second is specified.
If you change to 500 ms between checks and also check if the task is run for the specified code below. I think it will work fine.
Added in task.js:
function isAlreadyRun(date, lastDate){
if (lastDate){
return (
(date.getSeconds() === lastDate.getSeconds())&&
(date.getMinutes() === lastDate.getMinutes())&&
(date.getHours() === lastDate.getHours())&&
(date.getDate() === lastDate.getDate())&&
(date.getMonth() === lastDate.getMonth())&&
(date.getDay() === lastDate.getDay()));
}else{
return false;
}
}
and changed update function:
Task.prototype.update = function(date){
if(mustRun(this, date)&& !isAlreadyRun(date,this.lastDate)){
try {
this.lastDate = date;
this.execution();
} catch(err) {
console.error(err);
}
}
};

more tolerant handling of the schedule syntax

I had given the schedule like this:
cron.schedule('00 53 08 * * *', () => {
(00 instead of 0, and 08 instead of 8)
this schedule had not started at the expected time.

or as:
cron.schedule('10 53 8 * * *', () => {
(extra blanks)
this resulted in an exception is a invalid expression for hour

I would like node-cron to handle this more tolerant. especially the first must be handled, since it's not starting the task at the expected time without any warning.

Test failures with fresh install

node v6.10.1
npm 3.10.10
Linux

  89 passing (325ms)
  1 failing

  1) scheduling with range values should accept range values in hour:
     Error: expected 0 to equal 3
      at Assertion.assert (node_modules/expect.js/index.js:96:13)
      at Assertion.be.Assertion.equal (node_modules/expect.js/index.js:216:10)
      at Context.<anonymous> (test/range-values-test.js:35:25)

Tests ran at 2017-05-29 17:21

Get next execution time

I wonder if it's possible to add a method that returns the time of the next scheduled run (after the schedule has been started of course).
This could be a nice improvment for apps with a gui to check the current cron state.

Rogue Job

I have a single task scheduled twice daily (8am & 4pm). Now, I'm having an issue w/ the job running twice @ each scheduled time a few seconds apart. I've removed the task completely from my application and now it's running a single time as it should, but there is no reference to it in my application.

If it matters, my app was deployed w/ Dokku and I haven't established any caching mechanism.

how to apply gmt setting in node-cron

Hi,
rather than issue it is basically a question ?.

my server date is

Tue Apr 25 01:24:13 GMT+6 2017

and below is my config , but it is not working as expected !

var interncronset = cron.schedule('1 24 13 * * *' , function() {
   console.log('immediately started');
}, false);
interncronset.start();

any pointer on how to work as expected ,
Thanks in advance !

Day of month incorrect

Months in Cron should be 1-12 according to Cron documentation and the README. However, it actually is 0-11 in this package (presumably because months in JS are zero indexed). Take this schedule 16 8 3 10 * for example.

It should be October 3rd (see https://crontab.guru/#16_8_3_10_*).

But in reality it won't run till November. If I change 10 to 9, this will work in October.

Unique ID for cron

Thanks for the great module.

I have an application that dynamically creates crons based on user account input. I have had no problem creating the jobs dynamically. I just don't see a way to get/store a unique reference to the cron so later I can retrieve and stop/remove the cron is user wants to stop it. The only other module I have found that seems to do this is https://github.com/NineCollective/node-crontab but it seem much less supported and has some issues with have the same ID for multiple crons.

Are there currently any ways to do this with this module?

Thanks!

Day of week vs Day of month

Hey @merencia,

First of all, thank you so much for the library, very good job!

I wanted to ask you a question regarding the way node-cron is matching task against Day of week and Day of month.

In the specification of crontab, we have:

Finally, if either the month or day of month is specified as an element or list, and the day of week is also specified as an element or list, then any day matching either the month and day of month, or the day of week, shall be matched.
-- http://pubs.opengroup.org/onlinepubs/007904975/utilities/crontab.html

Which mean in your code we should have something like:

var runOnDay = false;
if (task.initialPatterns[3] === '*') {
   runOnDay = matchPattern(task.expressions[5], date.getDay());
} else if (task.initialPatterns[5] === '*')
   runOnDay = matchPattern(task.expressions[3], date.getDate());
} else {
   runOnDay = matchPattern(task.expressions[3], date.getDate()) || matchPattern(task.expressions[5], date.getDay());
}
return runInSecond && runOnMinute && runOnHour && runOnMonth && runOnDay;

With this.initialPatterns = pattern.split(' '); in the Task constructor.

I just want to highlight that node-cron does not match the standard specification of the crontab, which frankly I prefer since it helps us doing things like 0 10 1-7 * 1 = Every first Monday of the month at 10am.

So finally, my question. Could you either:

  1. put somewhere in the documentation that node-cron is not matching days like the standard for crontab
  2. or change the code to match the specification

Thanks,

How to stop executing the cron job on condition basis

I have a program which kicks in at 5pm everyday and runs for every 1min.. Now i want to make the task execution inside this scheduler to be condition based as follows-

var cron = require('node-cron');
var bool=false;
cron.schedule('*/1 17-17 * * *', function(){
console.log('running a task every minute for 15th hour');
if(bool)
{
console.log("bool is false now");
this.stop(); //-->Not sure of this
}
else{
console.log(new Date());
bool=true;
}
});

How can stop this task getting executed after 'bool' becomes false? I do not want to disable this job , as i want this to run every day at the same time but it should stop once the condition becomes false.. Please help..

How to increase the execution time ?

I have a script to run having hundreds of rest API calls for reporting purposes. can anyone please tell how to increase the execution time for this ? i believe there is limit to the execution time in node by default

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.