Coder Social home page Coder Social logo

sails-hook-cron's Introduction

sails-hook-cron

Build Status Coverage Downloads Downloads npm version

GitHub followers Twitter Follow

Sails hook for running cron tasks.

Getting Started

Install it via npm:

npm install sails-hook-cron

Configure config/cron.js in your project:

module.exports.cron = {
  myFirstJob: {
    schedule: '* * * * * *',
    onTick: function () {
      console.log('You will see this every second');
      console.log(`Also, sails object is available as this, e.g. ${this.config.environment}`);
    }
  }
};

Examples

Schedule field syntax is:

// ['seconds', 'minutes', 'hours', 'dayOfMonth', 'month', 'dayOfWeek']

module.exports.cron = {
  firstJob: {
    schedule: '30 47 15 17 may *',
    // in May 17 15:47:30 GMT-0300 (BRT)
    onTick: function() {
      console.log('I will trigger in May 17 15:47:30');
    },
    timezone: 'America/Sao_Paulo'
    // timezone Brazil example
  }
};

You can define cron tasks only with required fields:

module.exports.cron = {
  firstJob: {
    schedule: '* * * * * *',
    onTick: function() {
      console.log('I am triggering every second');
    }
  },

  secondJob: {
    schedule: '*/5 * * * * *',
    onTick: function() {
      console.log('I am triggering every five seconds');
    }
  }
};

You can define advanced fields:

module.exports.cron = {
  myJob: {
    schedule: '* * * * * *',
    onTick: function() {
      console.log('I am triggering when time is come');
    },
    onComplete: function() {
      console.log('I am triggering when job is complete');
    },
    start: true, // Start task immediately
    timezone: 'Ukraine/Kiev', // Custom timezone
    context: undefined, // Custom context for onTick callback
    runOnInit: true // Will fire your onTick function as soon as the request initialization has happened.
  }
};

You can get created jobs and start\stop them when you wish:

// config/cron.js
module.exports.cron = {
  myJob: {
    schedule: '* * * * * *',
    onTick: function() {
      console.log('I am triggering when time is come');
    },
    start: false
  }
};

// api/controllers/SomeController.js
module.exports = {
  someAction: function(req, res) {
    sails.hooks.cron.jobs.myJob.start();
    sails.hooks.cron.jobs.myJob.stop();
  }
};

Context

There are three states for the context, i.e. this on onTick call:

  • When you don’t declare context - this points to the Sails object.
  • If you declare it as a null (context: null), this points to the original context from the cron library.
  • Otherwise, if you declare a context with some object (context: {foo: 'bar'}), this will point to the object instead.

License

MIT

sails-hook-cron's People

Contributors

dependabot[bot] avatar ghaiklor avatar greenkeeper[bot] avatar greenkeeperio-bot avatar incocode avatar kerwood avatar makah avatar muriloqr avatar polyakovin 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

Watchers

 avatar  avatar  avatar  avatar  avatar

sails-hook-cron's Issues

Is it possible to pass arguments to jobs?

I want to use the cron jobs like this sails.hooks.cron.jobs.myJob.start(). Is it possible to somehow pass arguments to that instance of job? Has to do with the context field?

Non working example

onComplete is never called.

module.exports.cron = {
  myJob: {
    schedule: '* * * * * *',
    onTick: function() {
      console.log('I am triggering when time is come');
    },
    onComplete: function() {
      console.log('I am triggering when job is complete');
    },
    start: true, // Start task immediately
    timezone: 'Ukraine/Kiev', // Custom timezone
    context: undefined // Custom context for onTick callback
  }
};

local.js = bad instructions

It's bad instructions to tell people that they should use local.js for the global object. local.js is by default in .gitignore and not mean to be committed to SCM nor available in any other environment other than the local (hence the name) development environment.

The reason sails is not working is that you're calling an underlying library (cron) and passing in onTick from the config file. However, there is no context being set per cron instructions:

context - [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call this.stop(). However, if you change this you'll have access to the functions and values within your context object.

I believe that the sails object needs to be passed into context. I'm therefore proposing to modify the index.js so that it looks like this:

jobs.forEach(job => {
          this.jobs[job] = new CronJob(
            config[job].schedule,
            config[job].onTick,
            config[job].onComplete,
            typeof config[job].start === 'boolean' ? config[job].start : true,
            config[job].timezone,
            config[job].context || sails,
            typeof config[job].runOnInit === 'boolean' ? config[job].runOnInit : false
          );
        });

Then inside the config definition you use "this" to represent sails:

module.exports.cron = {
  testJob: {
    schedule: '* * * * * *',
    onTick: async function () {
      try {
        console.log(this.models); // returns all models available in sails object
      }catch(e){
        console.log(e);
      }
    }
  }
};

sails.config.environment

Is it posible to use sails.config.environment? Or I must to start the cron job from a controller, for example?

Thanks

Cron run twice or more based on the time the cron is saved

This project has https://www.npmjs.com/package/cron as dependency.
This dependency used to have a bug that was fixed when a new version was released.
But your last release still point to a version that contains this bug.

I saw in your dev branch that you have updated the dependency but no release was made since the update.

Do you have any idea when you pretend release?

Global Sails variable not avaliable within the onTick function

If anyone is stuck and can not successfully run your function by following the example in the readme.

Move the cron data from "config/cron.js" to "config/local.js". This way your function will have access to the Sails variable and to the waterline API as well.

Example function "config/local.js""

/**
 * Local environment settings
 *
 * Use this file to specify configuration settings for use while developing
 * the app on your personal system.
 *
 * For more information, check out:
 * https://sailsjs.com/docs/concepts/configuration/the-local-js-file
 */

module.exports = {

  // Any configuration settings may be overridden below, whether it's built-in Sails
  // options or custom configuration specifically for your app (e.g. Stripe, Mailgun, etc.)
  cron: {
    myJob: {
      schedule: '* * * * * *', // Runs every second
      onTick: async function() {
          console.log("cron ok");
          console.log(sails.config.port);
          var test = await Posts.find({});
          console.log(test)
      },
      start: true, // Start task immediately
      context: undefined, // Custom context for onTick callback
      runOnInit: true // Will fire your onTick function as soon as the requisit initialization has happened.
    }
  }

};

contexr

It may be interesting write a section on README about context. Something like:

There are three states for the context (this)

  1. If you don't declare context: this = sails
  2. If you declare context = underfined: this = original cron's library context
    You still access sails from global variable
  3. If you declare context = <any_object>: this = any_object (as we expect)

How to run cron on multiple servers?

Hello,

I'm running multiple servers at the time. If I create a cron job - it will run on all servers.

How to make it run only on one of servers?

Thank you.

Setting a job for */5 minutes runs it at 2.25~ minutes

/* globals Payment, sails */
var _ = require('lodash');
var async = require('async');

module.exports.cron = {
  emailJob: {
    schedule: '* */5 * * * *', // run every 5 minutes
    onTick: function () {
      // ...
    }
  }
};

this i would expect to run every 5 minutes, instead it seems its running every ~2.25 minutes

Replace schedule as a key with named job

When you are accessing to job via sails.hooks.cron you must set schedule as a key. Need to replace it with named job. So you will able do sails.hooks.cron.jobs.myJob.start().

Example:

// config/cron.js
module.exports.cron = {
  myJob: {
    schedule: '* * * * * *',
    onTick: function() {}
  }
};

Cron (month) issue

According to the official Cron page, the code below should be 9/18/2017 at 10:00 PM. Only problem is, in this hook month starts at 0, instead of 1.

module.exports.cron = {
    job: {
        schedule: '0 0 22 18 9 *',
        onTick: function() {
            console.log('Output');
        },
        timezone: 'America/New_York',
        start: true
    }
};

Basically the only way it would work for 9/18/2017 is if the following schedule variable is

schedule: '0 0 22 18 8 *',

https://en.wikipedia.org/wiki/Cron#Overview

TypeError: Cannot read property 'ok', 'send' of undefined

I got this error after cron calls my function from sails controller

//DataController.js
insertIncidents: async function(req, res)
    {
        let temp = await snow_data.getIncidents();
        try{
            for(let i=0;i<temp.result.length;i++)
            {
                let insert_query = await sails.sendNativeQuery("INSERT INTO fpt_it_test_database.open_incidents_table (Incident_Num, Priority, Description, Percent_SLA, Config_Item, Assigned_to, Datetime_created) VALUES ('"+temp.result[i].number+"', '"+temp.result[i].priority+"', '"+temp.result[i].short_description+"', '"+temp.result[i].made_sla+"','"+temp.result[i].subcategory+"', 'Nat', '"+temp.result[i].sys_created_on+"')");
            }
        }catch(error){
            // console.log(error);
        }
        console.log("Success");
        return res.ok("Success");
    },
//cron.js
const DataController = require('../api/controllers/DataController');
// const moment = require('moment');
// const datetime = moment().format('hh꞉mm꞉ssA');

module.exports.cron = {
    pullIncidents: {
        schedule: '*/3 * * * *',        // [REQUIRED]
        onTick: () => {                 // [REQUIRED]
            DataController.insertIncidents();
            console.log('You will see this every 3 minutes');
            // res.ok("Success");
        },
        timezone: 'Asia/Singapore', // [OPTIONAL] set timezone
        runOnInit: true,            // [OPTIONAL] fire onTick function as soon as the cron is initialized
        // start: false                // [OPTIONAL] manually start the cron task (DEFAULT = true) See below for the example
    }
};

how to pass parram to onTick function

i try to pass some params to ontick function in cron config like this :

//AgentController.js

module.exports = {

     var resultGetLiveAgentSerivce;
     var opts = {
        name : 'jefery'
     };
     var results = sails.hooks.cron.jobs.getLiveAgentJob.start(opts, function(err, results){
        resultGetLiveAgentSerivce: results;
        console.log(resultGetLiveAgentSerivce);
  });

};

//cron.js

module.exports.cron = {

  getLiveAgentJob:  {

      schedule: '*/5 * * * * *',

      onTick: function(option, callback) {

  console.log(option.name);
  var err = '';
  var results = '';


  //call service AgentService , function GetLiveAgents that return a query mysql 
  AgentService.GetLiveAgents(option.name, function(err, results){

    if(err){

      err =  err;
      return err;
    }

    if(results){

      results =  results;
      console.log(results);
     
    }
    });

},

start: false

}
};

option.name is undifened !!

schedule: '* * * * * *',

In README.md, you have

schedule: '* * * * * *',  // 6 fields!

and

schedule: '*/5 * * * *',   // 5 fields!

It should always be 5 fields, right?

Cron's run for 60 times!

Hello,

I'm setting a cron job and it's running for 60 times when the time comes.

module.exports.cron = {
    myJob: {
        schedule: '* */10 * * * *',
        onTick: function() {
            console.log("I am triggering when the time comes, but I'm doing it 60 times... It's VERY possible that I don't know how to configure jobs, but I'm not sure this time!");
        }
    }
};```

Cron scheduled dosen't run at all

sendKitchenUpdates: {
schedule: '02 0 * * *',
onTick: function() {
var moment = require("moment");
startLog(moment);
console.log('Cron Strarted');
//Day less than updated
dayCheck = 1;
getfirebasedata(dayCheck, moment);
},
// onComplete: function() {
// var moment = require("moment");
// console.log('completed');
// endLog(moment);
// },
start: false, // Start task immediately
timezone: 'Asia/Kolkata', // Custom timezone
}

Multi-server

This is awesome thanks for it! How does this work across multiple servers?

Is this hook cluster-safe?

I suppose jobs are executed in all nodes at the same time, or there is some class of syncronization (ie using Redis) to avoid that?

start: true doesn't start job

Perhaps I'm not understanding the documents correctly, however here is my job.

My expectation here is that this job will run every Sunday at 1am, however it will also run straight away when sails lifts. This doesn't appear to happen

  firstJob: {
    schedule: '0 0 1 * * 0',
    onTick: function() {
      console.log('I will trigger at 01:00 every Sunday');
    },
    timezone: 'America/Sao_Paulo',
    start: true,
  },

Loading jobs after initialization of sails

The problem I have: jobs don't have access to services and all global variables so they are not really convenient.

The idea how we can solve that: we can specify all jobs separately in api/jobs and load them in callback for sails.on('ready').

Does it work for you? If yes I can implement it quickly and send a PR.

cron jobs not running on digitalocean server.

Please help me.
I have created few cron jobs in sails 1.0 version.
and it was running on heroku app for 2 days only.
when I have deployed my application on digitalocean then it's not working any more.
please tell me what should i do?

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.