How to use cron - 10 common examples

To help you get started, weโ€™ve selected a few cron examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zeit / pkg / test / test-79-npm / cron / cron.js View on Github external
'use strict';

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

var counter = 0;

new CronJob('* * * * * *', function () { // eslint-disable-line no-new
  counter += 1;
}, null, true, 'America/Los_Angeles');

setTimeout(function () {
  if (counter === 4) console.log('ok');
  process.exit();
}, 4500);
github kalisio / krawler / src / cli.js View on Github external
.catch(error => {
        console.error(error.message)
        Healthcheck.isRunning = false
        Healthcheck.error = error
        // When not running job continuously stop the server
        if (!options.cron) {
          server.close()
        }
      })
  }

  // Setup CRON job if required
  let cronJob
  if (options.cron) {
    console.log('Scheduling job with cron pattern ' + options.cron)
    cronJob = new CronJob(options.cron, () => {
      // If last job has not yet finished skip this call as we are late
      if (!Healthcheck.isRunning) {
        Healthcheck.nbSkippedJobs = 0
        runJobWithOptions()
      } else {
        console.log('Skipping scheduled job as previous one is not yet finished')
        Healthcheck.nbSkippedJobs++
      }
    })
    // In case the server is forced to exit stop the job as well
    server.on('close', () => {
      cronJob.stop()
      console.log('Stopped scheduled job with cron pattern')
    })
  }
  // Run job
github bh-lay / blog / sys / cronJob.js View on Github external
// ๆฏๆ™šไธ‰็‚น
	new CronJob('01 01 03 * * *', function() {
		// ๆ›ดๆ–ฐๅฎž้ชŒๅฎค้‡Œ็š„Githubๆ•ฐๆฎ
		updateLabsDataFromGithub.all()
		// ๆ›ดๆ–ฐไธชไบบGithubไฟกๆฏ
		myGithubData.update()
		// ๆ›ดๆ–ฐๅ‰งไธญไบบ็š„ๆœ‹ๅ‹ๅœˆๆ•ฐๆฎ
		updateMoment.sync()
		// ๆ›ดๆ–ฐ720ไบ‘ๆ•ฐๆฎ
		my720Data.update()
		// ๆ›ดๆ–ฐๅ›พ่™ซๆ•ฐๆฎ
		myTuchongData.update()
	}, null, true, 'Asia/Hong_Kong')

	// ๆฏๆ™šไธ‰็‚น้›ถๅๅˆ†
	new CronJob('01 10 03 * * *', function() {
		// ๆธ…้™คๅ…จ้ƒจ็ผ“ๅญ˜
		app.cache.clear()
	}, null, true, 'Asia/Hong_Kong')
}
github agenda / agenda / lib / job.js View on Github external
const computeFromInterval = () => {
    debug('[%s:%s] computing next run via interval [%s]', this.attrs.name, this.attrs._id, interval);
    let lastRun = this.attrs.lastRunAt || new Date();
    lastRun = dateForTimezone(lastRun);
    try {
      const cronTime = new CronTime(interval);
      let nextDate = cronTime._getNextDateFrom(lastRun);
      if (nextDate.valueOf() === lastRun.valueOf()) {
        // Handle cronTime giving back the same date for the next run time
        nextDate = cronTime._getNextDateFrom(dateForTimezone(new Date(lastRun.valueOf() + 1000)));
      }
      this.attrs.nextRunAt = nextDate;
      debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
    } catch (e) {
      // Nope, humanInterval then!
      try {
        if (!this.attrs.lastRunAt && humanInterval(interval)) {
          this.attrs.nextRunAt = lastRun.valueOf();
          debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
        } else {
          this.attrs.nextRunAt = lastRun.valueOf() + humanInterval(interval);
          debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
github agenda / agenda / lib / job / compute-next-run-at.js View on Github external
const computeFromInterval = () => {
    debug('[%s:%s] computing next run via interval [%s]', this.attrs.name, this.attrs._id, interval);
    let lastRun = this.attrs.lastRunAt || new Date();
    lastRun = dateForTimezone(lastRun);
    try {
      const cronTime = new CronTime(interval);
      let nextDate = cronTime._getNextDateFrom(lastRun);
      if (nextDate.valueOf() === lastRun.valueOf() || nextDate.valueOf() <= previousNextRunAt.valueOf()) {
        // Handle cronTime giving back the same date for the next run time
        nextDate = cronTime._getNextDateFrom(dateForTimezone(new Date(lastRun.valueOf() + 1000)));
      }

      this.attrs.nextRunAt = nextDate;
      debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, new Date(this.attrs.nextRunAt).toISOString());
    // Either `xo` linter or Node.js 8 stumble on this line if it isn't just ignored
    } catch (error) { // eslint-disable-line no-unused-vars
      // Nope, humanInterval then!
      try {
        if (!this.attrs.lastRunAt && humanInterval(interval)) {
          this.attrs.nextRunAt = lastRun.valueOf();
          debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, new Date(this.attrs.nextRunAt).toISOString());
        } else {
github stelace / stelace / src / util / time.js View on Github external
function computeRecurringDates (pattern, { startDate, endDate, timezone = 'UTC' } = {}) {
  if (_.isNil(timezone)) timezone = 'UTC'

  if (!isDateString(startDate) || !isDateString(endDate)) {
    throw new Error('Expected start and end dates')
  }
  if (endDate < startDate) {
    throw new Error('Invalid dates')
  }

  const cronTime = new CronTime(pattern, timezone)

  let continueLoop = true
  const dates = []
  let cronISODate = new Date(new Date(startDate).getTime() - 1) // start from `startDate` minus 1 millisecond

  while (continueLoop) {
    // `_getNextDateFrom` is a private method from `CronTime.prototype`
    // Please check its availability when upgrading the library `cron`
    const cronMomentDate = cronTime._getNextDateFrom(cronISODate, timezone)

    cronISODate = cronMomentDate.toISOString()
    continueLoop = cronISODate < endDate

    if (continueLoop) {
      dates.push(cronISODate)
    }
github sbehrends / Live-WorldCup-Notification-for-Slack / bot.js View on Github external
var announceMatchComplete = function (match) {
    var vs = match.homeTeam + ' vs ' + match.awayTeam;
    var stadium = match.data.c_Stadidum + ', ' + match.data.c_City;
    var text = stopExpression + ' ' + slackLink(vs, match.url) + ' (' + stadium + ')';
    announce(text);
    delete(activeMatches[match.data.n_MatchID]);
};

/**
 * Sends a score summary message to slack.
 */
var announceScore = function (match) {
    announce(match.homeTeam + ' (' + match.score + ') ' + match.awayTeam);
};

var cronJob = cron.job("*/5 * * * * *", function(){


      // Get Match list
      requestify.get('http://live.mobileapp.fifa.com/api/wc/matches').then(function(response) {
            var matches = response.getBody().data.second;

            async.filter(matches, function(item, callback) {
               callback (item.b_Live == true || activeMatches[item.n_MatchID]);

      }, function(results){
          for (var i = 0; i < results.length; i += 1) {
              if (activeMatches[results[i].n_MatchID]) {
                  match = activeMatches[results[i].n_MatchID];
              } else {
                  match = new Match(language);
                  match.on('startMatch', announceMatchStart);
github z1c0 / dashydash / src / components / modules / birthdays / birthdays.js View on Github external
init: function () {
    // each day at 10 AM
    const cronJob = cron.job("0 0 10 * * *", () => {
      sendNotification();
    });
    cronJob.start();
  },
github winderica / KanColleSource / utils / detector.js View on Github external
const cron = require('cron');
const fetch = require('node-fetch');
const { promisify } = require('util');
const fs = require('fs').promises;
const exec = promisify(require('child_process').exec);
const beautify = require('js-beautify').js;
const chunker = require('./chunker');
const searcher = require('./searcher');
const logger = require('./logger');
const jsStyle = require('../style');
const jsonStyle = {
    "indent_size": "2",
    "eol": "\r\n",
};
const detector = cron.job("0 */30 * * * *", async () => {
    try {
        const gameConsts = await (await fetch('http://203.104.209.7/gadget_html5/js/kcs_const.js')).text();
        const version = gameConsts.match(/\d\.\d\.\d\.\d/)[0];
        const currentVersion = await fs.readFile('../version');
        if (version !== currentVersion.toString()) {
            logger.info(`Detected main.js v${version}`);
            const script = await (await fetch(`http://203.104.209.71/kcs2/js/main.js?version=${version}`)).text();
            await fs.writeFile(`../raw.js`, script);
            await fs.writeFile(`../main.js`, beautify(script, jsStyle));
            await fs.writeFile('../version', version);
            const functions = /}\((\[function.*)\).default/s.exec(script)[1];
            chunker(eval(functions)); // haven't find a better way to parse array of functions
            const start = /=\s*(\d*)\)\s*}\(\[/.exec(script)[1];
            await fs.writeFile('../tree.json', beautify(JSON.stringify(searcher(start)), jsonStyle));
            const { stdout, stderr } = await exec(`"../push.sh" "Update: main.js v${version}"`);
            logger.info(stdout);
github z1c0 / dashydash / src / components / modules / pics / pics.js View on Github external
init : function() {
    // every hour
    var cronJob = cron.job("0 0 */1 * * *", function() {
      checkForNewPhotos(config);
    });
    cronJob.start();
    checkForNewPhotos(config);
  },

cron

Cron jobs for your node

MIT
Latest version published 4 months ago

Package Health Score

94 / 100
Full package analysis