Example #1
0
 }
 exports.getJWCImportentData = function(){
	getJWCImportentData();
 }

// getJWCImportentData();
// getCUITImportentDataByAV();

//初始化并设置定时任务的时间
// var rule = new schedule.RecurrenceRule();
// rule.second  = 5;
var rule = '0 0/1 9-23 * * ?'

//处理要做的事情
var j = schedule.scheduleJob(rule, function(){
    // console.log('我在这里处理了某些事情...');
    getCUITImportentData();
});


// var url = "http://www1.cuit.edu.cn/NewsList.asp?bm=32&type=448";
// http.get(url, function(res) {
//     var source = "";
// 		res.setEncoding('binary');
//     res.on('data', function(data) {
//         source += data;
//     });
//     res.on('end', function() {
// 				var buf = new Buffer(source, 'binary');
// 				var str = iconv.decode(buf, 'GBK');
// 				$ = cheerio.load(str);
// 				var time = '';
require('./pRequire');
var schedule = require('node-schedule');

function createCronJob(time, onTick, onComplete){
  var cronJob = new CronJob({
    cronTime  : time,
    onTick    : onTick,
    onComplete: onComplete,
    start     : false,
    timeZone  : 'CET'
  });
  return cronJob;
}

schedule.scheduleJob('41 14 * * *', function(){
    console.log('The answer to life, the universe, and everything!');
});

(function initCron(handler) {
  var loadCredentials = require('./../credentials').loadCredentials;
  var log             = pRequire('/lib/log');
  var process         = require('process');

  loadCredentials(function(err, credentials) {
    if(err) { throw err; }

    var global = require('./global');

    global.setCredentials(credentials);

    var orm    = pRequire('/orm');
    orm.init(function() {
      var Seo     = pRequire('/managers/seo-manager').seoManager;
      var ML      = pRequire('/managers/mailing-list-manager').mailingLists;

      var running = ' cron job is now runnning!!';
      var stopped = ' cron job stopped!!!';

      var cronTimes = {
        d15: '00 15 04 * * *',
        d30: '00 30 04 * * *',
        d45: '00 45 04 * * *',
        e00: '00 00 05 * * *',
        e30: '00 30 05 * * *',
        f00: '00 00 06 * * *',
        f30: '00 30 06 * * *',
        g00: '00 00 07 * * *',
        g15: '00 15 07 * * *',
        g30: '00 30 07 * * *',
        g4: '00 45 07 * * *',
        h: '00 00 08 * * *',
        i: '00 00 09 * * *',
        j: '00 30 09 * * *',
        k: '00 00 10 * * *',
        l: '00 15 10 * * *'
      };

      //updateTopTagsMatView cron job runs daily at 04:15
      schedule.scheduleJob(cronTimes.d15,
        function() {
          log.info('updateTopTagsMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_top_tags_view')
            .query('REFRESH MATERIALIZED VIEW materialized_top_tags_view;',
              function() {
                log.info('updateTopTagsMatView', stopped, 'process # ', process.pid);
              });
        });

      //updateSongMatView cron job runs daily at 04:30
      schedule.scheduleJob(cronTimes.d30,
        function() {
          log.info('updateSongMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_song_view')
            .query('REFRESH MATERIALIZED VIEW materialized_song_view;',
              function() {
                log.info('updateSongMatView', stopped, 'process # ', process.pid);
              });
        });

      //updateSongMatView cron job runs daily at 04:45
      schedule.scheduleJob(cronTimes.d45,
        function() {
          log.info('updateTopSongsMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_top_songs_view')
            .query('REFRESH MATERIALIZED VIEW materialized_top_songs_view;',
              function() {
                log.info('updateTopSongsMatView', stopped, 'process # ', process.pid);
              });
        });

      // addGaveUpUsers cron job runs daily at 05:00
      schedule.scheduleJob(cronTimes.e00,
        function() {
          log.info('addGaveUpUsers', running, 'process # ', process.pid);
          ML.addGaveUpUsersToQueue().then(function() {
            log.info('addGaveUpUsers', stopped, 'process # ', process.pid);
          });
        });

      // addNoNewSongsUsers cron job runs daily at 05:30
      schedule.scheduleJob(cronTimes.e30,
        function() {
          log.info('addNoNewSongsUsers', running, 'process # ', process.pid);
          ML.addNoNewSongsUsersToQueue().then(function() {
            log.info('addNoNewSongsUsers', stopped, 'process # ', process.pid);
          });
        });

      // addNoSongsUsers cron job runs daily at 06:00
      schedule.scheduleJob(cronTimes.f00,
        function() {
          log.info('addNoSongsUsers', running, 'process # ', process.pid);
          ML.addNoSongsUsersToQueue().then(function() {
            log.info('addNoSongsUsers', stopped, 'process # ', process.pid);
          });
        });

      // cron job runs daily at 06:30
      schedule.scheduleJob(cronTimes.f30,
        function() {
          log.info('addUsersWith10Songs', running, 'process # ', process.pid);
          ML.addUsersWith10SongsToQueue().then(function() {
            log.info('addUsersWith10Songs', stopped, 'process # ', process.pid);
          });
        });

      // addNewUsersMainList cron job runs daily at 07:00
      schedule.scheduleJob(cronTimes.g00,
        function() {
          log.info('addNewUsersMainList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(1, ML.mailingListsNames.mainList)
            .then(function() {
              log.info('addNewUsersMainList', stopped, 'process # ', process.pid);
            });
        });

      // addNewUsersToStudioList cron job runs daily at 07:15
      schedule.scheduleJob(cronTimes.g15,
        function() {
          log.info('addNewUsersToStudioList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(2, ML.mailingListsNames.studioList).then(function() {
            log.info('addNewUsersToStudioList', stopped, 'process # ', process.pid);
          });
        });

      // addNewUsersToRegistration cron job runs daily at 07:30
    schedule.scheduleJob(cronTimes.g30,
      function() {
        log.info('addNewUsersToRegistration', running, 'process # ', process.pid);

        ML.addNewUsersToRegistrationLists(3, ML.mailingListsNames.expressList).then(function() {
          log.info('addNewUsersToRegistration', stopped, 'process # ', process.pid);
        });
      });

      // addNewUsersToOthersList cron job runs daily at 07:45
      schedule.scheduleJob(cronTimes.g4,
        function() {
          log.info('addNewUsersToOthersList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(4, ML.mailingListsNames.mainList).then(function() {
            log.info('addNewUsersToOthersList', stopped, 'process # ', process.pid);
          });
        });

      // addUsersToMailingList cron job runs daily at 08:00
      schedule.scheduleJob(cronTimes.h,
        function() {
          log.info('addUsersToMailingList', running, 'process # ', process.pid);

          ML.addUsersToMailingList().then(function() {
            log.info('addUsersToMailingList', stopped, 'process # ', process.pid);
          });
        });

      // createProfileIndexes cron job runs daily at 09:00
      schedule.scheduleJob(cronTimes.i,
        function() {
          log.info('createProfileIndexes', running, 'process # ', process.pid);

          Seo.createProfileIndexPages().then(function() {
            log.info('createProfileIndexes', stopped, 'process # ', process.pid);
          });
        });

      // createSongsIndexes cron job runs daily at 09:30
      schedule.scheduleJob(cronTimes.j,
        function() {
          log.info('createSongsIndexes', running, 'process # ', process.pid);

          Seo.createSongsIndexPages().then(function() {
            log.info('createSongsIndexes', stopped, 'process # ', process.pid);
          });
        });

      // createSitemapsIndex cron job runs daily at 10:00
      schedule.scheduleJob(cronTimes.k,
        function() {
          log.info('createSitemapsIndex', running, 'process # ', process.pid);

          Seo.createSitemapsIndexPage().then(function() {
            log.info('createSitemapsIndex', stopped, 'process # ', process.pid);
          });
        });

      //uploadSiteMaps cron job runs daily at 10:15
      schedule.scheduleJob(cronTimes.l, function() {
        log.info('uploadSiteMaps', running, 'process # ', process.pid);
        Seo.uploadSiteMaps().then(function() {
          log.info('uploadSiteMaps', stopped, 'process # ', process.pid);
          });
        });
    });
SyncShop();

/**
 *  定时拉取粉丝信息(每天6:00)
 **/
var ruleFans = new schedule.RecurrenceRule();
ruleFans.dayOfWeek = [0, new schedule.Range(1, 6)];
ruleFans.hour = 6;
ruleFans.minute = 0;
//var fansTimes = [];
//for (var j = 0; j < 60; j = j + 1) {
//    fansTimes.push(i);
//}
//ruleFans.minute = fansTimes;
var fansJob = schedule.scheduleJob(ruleFans, function () {
    SyncFans();
});

/**
 *  同步粉丝
 **/
function SyncFans() {
    var Fans = require('../lib/fans.js');
    var fans = new Fans();
    fans.getFans(0, '');
}

/**
 *  同步卡券
 **/
function SyncCard() {
Example #5
0
var j = schedule.scheduleJob(' */1440 * * * *', function(){
	
	var topguys = [];
	
	 var trendingQ = new Parse.Query('_User');
	trendingQ.limit(10);
	var top10featured;
	trendingQ.descending( "TrendingIndicator");
	
	
	 trendingQ.find({
  success: function(resultsT) {
 
  
 
var counter = 0;
   for (var i = 0; i < resultsT.length; i++) {
  
    var userData = resultsT[i];
	 
	   var name = userData.get("username");
	  topguys.push(name);
	   console.log('wel esem houwe ' + topguys[i] + 'aw' + name);
   }
	  
	    var FeaturedList = Parse.Object.extend("Featured");  
var featuredList = new FeaturedList();  
    console.log('SAMIRRRR ');
	  console.log('Janaa ' + topguys[i]);
featuredList.set("FeaturedTop", topguys);
featuredList.save(null, {
    success: function(featuredList) {
        console.log("update succeed");
    }
});
	  
		 var userQuery = new Parse.Query('_User');
	userQuery.limit(1000);
	
	userQuery.greaterThanOrEqualTo( "TrendingIndicator",0);
	
	
	 userQuery.find({
  success: function(results) {
 
  
 
var counter = 0;
   for (var i = 0; i < results.length; i++) {
  
    var userData = results[i];
    userData.set('TrendingIndicator',0);
    userData.save(null, { useMasterKey: true });
	   counter++;
    
     
   }
    res.success('I passed on '+counter + ' users');
   
     
  
  },

  error: function(error) {
    // error is an instance of Parse.Error.
  }
});
  
  
	
  },

  error: function(error) {
    // error is an instance of Parse.Error.
  }
});
	
	

});
Example #6
0
 * Module dependencies.
 */
 
 var schedule = require('node-schedule');
 var log = require('../logger/logger').LOG;

/**
 * Local Module dependencies
 */
 
var schedulerService = require("./scheduler-service");
var commonPror = require("../config.json").common;

// var CORNRULE = "10,20,30,40 * * * *";
// every Sunday at 2:30pm : {hour: 14, minute: 30, dayOfWeek: 0}
var recurrenceRule = commonPror.recurrenceRule;

//every Sunday at 2:30pm:
var job = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function() {
	schedulerService.runScheduler();
});


exports.runScheduler = function() {
	log.info('Manually started scheduler ... ');
	schedulerService.runScheduler();
}

exports.cancel = function() {
	job.cancel();
}
Example #7
0
};


exports.view_sensors = function(req, res){	
	/*
	 for(var j=0, sensor_list_len=sensor_list.length; j<sensor_list_len; j++){
		var sensor = sensor_list[j];
		console.log('\n');
		console.log('Id: '+sensor.id);
		console.log('Name: '+sensor.name);
		console.log('Host: '+sensor.sensor_host);
		console.log('State: '+sensor.state);
		console.log('\n');
	}
	*/
	
	res.send({sensors:sensor_list});
};

function addSensorToDb(sensor){
	mongo.save_sensor(sensor);
}

var rule = new schedule.RecurrenceRule();
rule.second = [10,20,30,40,50,59];
 
var j = schedule.scheduleJob(rule, function(){
	for (var i=0, len = sensor_list.length; i<len; i++){
		sensor_list[i].data = sensor_data.get_all_pollutants_by_sensor_id(sensor_list[i].data_id);
	}
});
Example #8
0
functions.scheduleUploadYoutube = function(date, job, mongoId, title ,description, keywords){
   scheduler.scheduleJob(date, function(m, t, d, k){
      return job(m,t,d,k);
   }.bind(null, mongoId, title,description, keywords ));
}
Example #9
0
config.scheduledTasks.forEach(function(task, index) {

	if (task.interval) {

		if (!interval) {

			interval = new Intervals({

				pulse: 120,
				autoStart: true
			});
		}

		winston.info("Starting %d sec interval job for: %s", task.interval, task.endpoint);

		var result = interval.addJob({

			route: config.baseUrl + task.endpoint, 
			interval: task.interval, 
			callback: function(err, result) {

				if (err) {

					winston.error("Failed task: %s", task.endpoint);
					consoleDump(err);
					consoleDump(result);

				} else {

					winston.info("Completed task: %s", task.endpoint);
					// winston.info(result.body);
				}
			}
		});

		if (result.message && result.stack) {
			winston.error(consoleDump(result));
		}

	} else {

		winston.info("Starting a job for '%s' with schedule: Minute: %d, Hour: %d, Day: %s", task.endpoint, task.minute, task.hour, task.day || "everyday");

		var scheduleOpts = {

			minute: typeof task.minute == "undefined" ? null : task.minute,
			hour: typeof task.hour == "undefined" ? null : task.hour,
			dayOfWeek: typeof task.day == "undefined" ? null : task.day
		};

		consoleDump(scheduleOpts);

		var job = schedule.scheduleJob(scheduleOpts, function() {

			request.get(config.baseUrl + task.endpoint, function(err, result, body) {

				if (err || result.statusCode != 200) {

					winston.error("Failed task: %s", task.endpoint);
					consoleDump(err);
					consoleDump({result: result, body: body});

				} else {

					winston.info("Completed task: %s", task.endpoint);
					// winston.info(body);
				}
			});
		});

		winston.info("Next Invocation of %s: %s", task.endpoint, job.nextInvocation().toString());
	}
});
Example #10
0
functions.scheduleUploadSoundcloud = function(date, job, title, mongoId, list, description, genre){
   scheduler.scheduleJob(date, function(t, m, l, d, g){
      return job(t, m ,l ,d, g);
   }.bind(null,title, mongoId, list, description, genre ));
}
Example #11
0
functions.scheduleFBPostWithPhoto = function(date, job, message, photoId){
   scheduler.scheduleJob(date, function(p,m){
      return job(p, m);
   }.bind(null,photoId,  message));

}
Example #12
0
/*
	Routing configs
*/
var router = express.Router();
require('./routes/router.js')(router, util, bodyParser);
app.use('/', router);

/*
    Wordpress Scraping Schedule (10mins)
*/

job.fetchAllBlogs(function(d) {
    storage.wordpress.storePosts(d);
    console.log('blogs scraped'.white);
});
var j = schedule.scheduleJob('0,10 * * * *', function() {
    job.fetchAllBlogs(function(d) {
        storage.wordpress.storePosts(d);
        console.log('blogs scraped'.white);
    });
});

/*
	init server
*/
http.createServer(app).listen(app.get('port'), function() {
    console.log();
    console.log('  OpenBCI Server Running  '.white.inverse);
    var listeningString = '  Listening on port ' + app.get('port') + "  ";
    console.log(listeningString.cyan.inverse);
});
    orm.init(function() {
      var Seo     = pRequire('/managers/seo-manager').seoManager;
      var ML      = pRequire('/managers/mailing-list-manager').mailingLists;

      var running = ' cron job is now runnning!!';
      var ended   = ' cron job ended!!';
      var stopped = ' cron job stopped!!!';

      var cronTimes = {
      a : '00 07 12 * * *',
      b : '00 30 04 * * *',
      b2: '00 45 04 * * *',
      c : '00 00 05 * * *',
      d : '00 30 05 * * *',
      e : '00 00 06 * * *',
      f : '00 30 06 * * *',
      g1: '00 00 07 * * *',
      g2: '00 15 07 * * *',
      g3: '00 30 07 * * *',
      g4: '00 45 07 * * *',
      h : '00 00 08 * * *',
      i : '00 00 09 * * *',
      j : '00 30 09 * * *',
      k : '00 00 10 * * *',
      l : '00 15 10 * * *'
      };

      //updateTopTagsMatView cron job runs daily at 04:15
      schedule.scheduleJob(cronTimes.a,
        function() {
          log.info('updateTopTagsMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_top_tags_view')
            .query('REFRESH MATERIALIZED VIEW materialized_top_tags_view;',
              function() {
                log.info('updateTopTagsMatView', ended);
              });
        });
        
      //updateSongMatView cron job runs daily at 04:30
      var updateSongMatView = createCronJob(cronTimes.b,
        function() {
          log.info('updateSongMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_song_view')
            .query('REFRESH MATERIALIZED VIEW materialized_song_view;',
              function() {
                log.info('updateSongMatView cron job ended');
                updateSongMatView.stop();
              });
        },
        function() {
          log.info('updateSongMatView', stopped, 'process # ', process.pid);
        });
      updateSongMatView.start();

      //updateSongMatView cron job runs daily at 04:45
      var updateTopSongsMatView = createCronJob(cronTimes.b2,
        function() {
          log.info('updateTopSongsMatView', running, 'process # ', process.pid);

          orm.getModel('materialized_top_songs_view')
            .query('REFRESH MATERIALIZED VIEW materialized_top_songs_view;',
              function() {
                log.info('updateTopSongsMatView cron job ended');
                updateTopSongsMatView.stop();
              });
        },
        function() {
          log.info('updateTopSongsMatView', stopped, 'process # ', process.pid);
        });
      updateTopSongsMatView.start();

      // addGaveUpUsers cron job runs daily at 05:00
      var addGaveUpUsers = createCronJob(cronTimes.c,
        function() {
          log.info('addGaveUpUsers', running, 'process # ', process.pid);
          ML.addGaveUpUsersToQueue().then(function() {
            addGaveUpUsers.stop();
          });
        },
        function() {
          log.info('addGaveUpUsers', stopped, 'process # ', process.pid);
        });
      addGaveUpUsers.start();

      // addNoNewSongsUsers cron job runs daily at 05:30
      var addNoNewSongsUsers = createCronJob(cronTimes.d,
        function() {
          log.info('addNoNewSongsUsers', running, 'process # ', process.pid);
          ML.addNoNewSongsUsersToQueue().then(function() {
            addNoNewSongsUsers.stop();
          });
        },
        function() {
          log.info('addNoNewSongsUsers', stopped, 'process # ', process.pid);
        });
      addNoNewSongsUsers.start();

      // addNoSongsUsers cron job runs daily at 06:00
      var addNoSongsUsers = createCronJob(cronTimes.e,
        function() {
          log.info('addNoSongsUsers', running, 'process # ', process.pid);
          ML.addNoSongsUsersToQueue().then(function() {
            addNoSongsUsers.stop();
          });
        },
        function() {
          log.info('addNoSongsUsers', stopped, 'process # ', process.pid);
        });
      addNoSongsUsers.start();

      // cron job runs daily at 06:30
      var addUsersWith10Songs = createCronJob(cronTimes.f,
        function() {
          log.info('addUsersWith10Songs', running, 'process # ', process.pid);
          ML.addUsersWith10SongsToQueue().then(function() {
            addUsersWith10Songs.stop();
          });
        },
        function() {
          log.info('addUsersWith10Songs', stopped, 'process # ', process.pid);
        });
      addUsersWith10Songs.start();

      // addNewUsersMainList cron job runs daily at 07:00
      var addNewUsersMainList = createCronJob(cronTimes.g1,
        function() {
          log.info('addNewUsersMainList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(1, ML.mailingListsNames.mainList)
            .then(function() {
              addNewUsersMainList.stop();
            });
        },
        function() {
          log.info('addNewUsersMainList', stopped, 'process # ', process.pid);
        });
      addNewUsersMainList.start();

      // addNewUsersToStudioList cron job runs daily at 07:15
      var addNewUsersToStudioList = createCronJob(cronTimes.g2,
        function() {
          log.info('addNewUsersToStudioList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(2, ML.mailingListsNames.studioList).then(function() {
            addNewUsersToStudioList.stop();
          });
        },
        function() {
          log.info('addNewUsersToStudioList', stopped, 'process # ', process.pid);
        });
      addNewUsersToStudioList.start();

      // addNewUsersToRegistration cron job runs daily at 07:30
    var addNewUsersToRegistration = createCronJob(cronTimes.g3,
      function() {
        log.info('addNewUsersToRegistration', running, 'process # ', process.pid);

        ML.addNewUsersToRegistrationLists(3, ML.mailingListsNames.expressList).then(function() {
          addNewUsersToRegistration.stop();
        });
      },
      function() {
        log.info('addNewUsersToRegistration', stopped, 'process # ', process.pid);
      });
    addNewUsersToRegistration.start();

      // addNewUsersToOthersList cron job runs daily at 07:45
      var addNewUsersToOthersList = createCronJob(cronTimes.g4,
        function() {
          log.info('addNewUsersToOthersList', running, 'process # ', process.pid);

          ML.addNewUsersToRegistrationLists(4, ML.mailingListsNames.mainList).then(function() {
            addNewUsersToOthersList.stop();
          });
        },
        function() {
          log.info('addNewUsersToOthersList', stopped, 'process # ', process.pid);
        });
      addNewUsersToOthersList.start();

      // addUsersToMailingList cron job runs daily at 08:00
      var addUsersToMailingList = createCronJob(cronTimes.h,
        function() {
          log.info('addUsersToMailingList', running, 'process # ', process.pid);

          ML.addUsersToMailingList().then(function() {
            addUsersToMailingList.stop();
          });
        },
        function() {
          log.info('addUsersToMailingList', stopped, 'process # ', process.pid);
        });
      addUsersToMailingList.start();

      // createProfileIndexes cron job runs daily at 09:00
      var createProfileIndexes = createCronJob(cronTimes.i,
        function() {
          log.info('createProfileIndexes', running, 'process # ', process.pid);

          Seo.createProfileIndexPages().then(function() {
            createProfileIndexes.stop();
          });
        },
        function() {
          log.info('createProfileIndexes', stopped, 'process # ', process.pid);
        });
      createProfileIndexes.start();

      // createSongsIndexes cron job runs daily at 09:30
      var createSongsIndexes = createCronJob(cronTimes.j,
        function() {
          log.info('createSongsIndexes', running, 'process # ', process.pid);

          Seo.createSongsIndexPages().then(function() {
            createSongsIndexes.stop();
          });
        },
        function() {
          log.info('createSongsIndexes', stopped, 'process # ', process.pid);
        });
      createSongsIndexes.start();

      // createSitemapsIndex cron job runs daily at 10:00
      var createSitemapsIndex = createCronJob(cronTimes.k,
        function() {
          log.info('createSitemapsIndex', running, 'process # ', process.pid);

          Seo.createSitemapsIndexPage().then(function() {
            createSitemapsIndex.stop();
          });
        },
        function() {
          log.info('createSitemapsIndex', stopped, 'process # ', process.pid);
        });
      createSitemapsIndex.start();

      //uploadSiteMaps cron job runs daily at 10:15
      var uploadSiteMaps = createCronJob(cronTimes.l, function() {
        log.info('uploadSiteMaps', running, 'process # ', process.pid);
        Seo.uploadSiteMaps().then(function() {
            uploadSiteMaps.stop();
          });
        },
        function() {
          log.info('uploadSiteMaps', stopped, 'process # ', process.pid);
        });
      uploadSiteMaps.start();
    });
Example #14
0
}).startRTM();


var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [1, 2, 3, 4, 5];
rule.hour = 18;
rule.minute = 0;

var j = schedule.scheduleJob(rule, function(){

  var now = new Date();

  var currentDay = days[now.getDay()];
  console.log("Dia actual " + currentDay);

  firebase.database().ref('almuerzos/').once('value').then(function(snapshot){
    var almuerzo = snapshot.val();
    console.log("Objecto almuerzo %j", almuerzo);
    bot.say({text: "Ya son las 12 medio dia, hora de comer, les recuerdo que hoy tenemos de comer " + almuerzo[currentDay],
                      channel:"C11429SQ6"});
  });
});

controller.hears(['cuenteme algo', 'cuenteme un chiste', 'cuente un chiste', 'estoy aburrido'], 'direct_message,direct_mention,mention', function(bot, message){
  var stories = ['- Mama que haces en frente de la computadora con los hojos cerrados??? \n- Nada hijo es que Windows me dijo que cierre las pestañas',
                 'Un hombre está haciendo un vuelo en un globo aerostático.' +
                 'Se extravía y decide descender y preguntar a alguien. Baja a ' +
                 'unos 10 metros del suelo y pregunta a una persona que pasaba por allí: \n' +
                 '- Por favor, ¿puede decirme donde estoy?\n' +
                 '- Pues mire, está usted en un globo aerostático, a unos 10 metros del suelo.\n'+
                 '- Usted es informático, ¿verdad?\n'+
Example #15
0
File: cron.js Project: sapetti/mans
module.exports = function(notifications, dataManager) {
    // Declare
    var cron = require('node-schedule');
    var max_accepted = dataManager.getMaxPlaces();
    
    //Notification schedule for Functional Training
    var FUNCTIONAL_PREVIOUS_DAY_18_TO_22 = {hour: [18, 19, 20, 21, 22], minute: 30, dayOfWeek: dataManager.getFunctionalDay()-1};
    var FUNCTIONAL_DAY_10_TO_17 = {hour: [10, 11, 12, 13, 14, 15, 16, 17], minute: 30, dayOfWeek: dataManager.getFunctionalDay()};
    var FUNCTIONAL_DAY_LAST_CALL = {hour: 18, minute: 0, dayOfWeek: dataManager.getFunctionalDay()};
    var FUNCTIONAL_DAY_RENEW_SESSION = {hour: 1, minute: 0, dayOfWeek: dataManager.getFunctionalDay()+1};
    
    //Notification schedule for Pilates
    var PILATES_PREVIOUS_DAY_18_TO_22 = {hour: [18, 19, 20, 21, 22], minute: 30, dayOfWeek: dataManager.getPilatesDay()-1};
    var PILATES_DAY_10_TO_17 = {hour: [10, 11, 12, 13, 14, 15, 16, 17], minute: 30, dayOfWeek: dataManager.getPilatesDay()};
    var PILATES_DAY_LAST_CALL = {hour: 18, minute: 0,  dayOfWeek: dataManager.getPilatesDay()};
    var PILATES_DAY_RENEW_SESSION = {hour: 1, minute: 0, dayOfWeek: dataManager.getPilatesDay()+1};
    
    //cronjobs for Functional
    cron.scheduleJob(FUNCTIONAL_PREVIOUS_DAY_18_TO_22, function(){
            console.log('Scheduled notifications... FUNCTIONAL_PREVIOUS_DAY_18_TO_22');
            sendNotifications(dataManager.getFunctional(), 'Entrenamiento funcional', false);
        });
    
    cron.scheduleJob(FUNCTIONAL_DAY_10_TO_17, function(){
            console.log('Scheduled notifications... FUNCTIONAL_DAY_10_TO_17');
            sendNotifications(dataManager.getFunctional(), 'Entrenamiento funcional', false);
        });
    
    cron.scheduleJob(FUNCTIONAL_DAY_LAST_CALL, function(){
            console.log('Scheduled notifications... FUNCTIONAL_DAY_LAST_CALL');
            sendNotifications(dataManager.getFunctional(), 'Entrenamiento funcional', true);
        });
    
    cron.scheduleJob(FUNCTIONAL_DAY_RENEW_SESSION, function(){
            console.log('Scheduled bulk data... FUNCTIONAL_DAY_RENEW_SESSION');
            // bulk functional workout info with news session date
            dataManager.bulkData(dataManager.getFunctional());
        });
    
    
    //cronjobs for Pilates
    cron.scheduleJob(PILATES_PREVIOUS_DAY_18_TO_22, function(){
            console.log('Scheduled notifications... PILATES_PREVIOUS_DAY_18_TO_22');
            sendNotifications(dataManager.getPilates(), 'Pilates', false);
        });
    
    cron.scheduleJob(PILATES_DAY_10_TO_17, function(){
            console.log('Scheduled notifications... PILATES_DAY_10_TO_17');
            sendNotifications(dataManager.getPilates(), 'Pilates', false);
        });
    
    cron.scheduleJob(PILATES_DAY_LAST_CALL, function(){
            console.log('Scheduled notifications... PILATES_DAY_LAST_CALL');
            sendNotifications(dataManager.getPilates(), 'Pilates', true);
        });
    
    cron.scheduleJob(PILATES_DAY_RENEW_SESSION, function(){
            console.log('Scheduled bulk data... PILATES_DAY_RENEW_SESSION');
            // bulk pilates workout info with news session date
            dataManager.bulkData(dataManager.getPilates());
        });
    
    /**
     * This function loops the users retrieved from the dataManager for the given workout and
     * filters what of them are accepted, rejected or reserve accepted in the last call.
     * After that, if it is the time ask to the notification service to send the notification mails.
     * -type: workout type
     * -workout_title: title to display in the mail
     * -lastCall: true if it is the lastCall that will be done for the users for the given workout session
     * @method
     */
    function sendNotifications(type, workout_title, lastCall) {
        var accepted = [];
        var rejected = [];
        var count = 0;
        dataManager.getWorkout(type, false, function(data) {
            //review which users will be accepted in the workout and which ones will be rejected
            var users = data.users;
            for(var i=0;i<users.length;i++) {
                if(!users[i].waitList && count<max_accepted) {
                    if(!users[i].notified) {
                        accepted.push(users[i]);
                    }
                    count++;
                } else if(!users[i].notified) {
                    rejected.push(users[i]);
                }
            }
            
            //notify those accepted users that were not notified previously
            notifications.sendAcceptedMail(accepted, data.date, workout_title, function() {
                dataManager.updateUserOnProperty(accepted,type,'notified',true);
            });
            
            if(count>=max_accepted) {
                //all places are ocupated, send rejected mails to all rejected users
                notifications.sendRejectedMail(rejected, data.date, workout_title, function() {
                    dataManager.updateUserOnProperty(rejected,type,'notified',true);
                });
                
            } else if(lastCall) {
                //it is last call, but there are remaining places in the workout
                var lastCallUsers = [];
                for(var j=count;j<max_accepted;j++){
                    //fill the remaining places
                    lastCallUsers.push(rejected.splice(0,1)[0]);
                }
                //notify new accepted users
                notifications.sendAcceptedMail(lastCallUsers, data.date, workout_title, function() {
                    dataManager.updateUserOnProperty(lastCallUsers,type,'notified',true);
                    dataManager.updateUserOnProperty(lastCallUsers,type,'waitList',false);
                });
                
                //notify finally rejected users
                notifications.sendRejectedMail(rejected, data.date, workout_title, function() {
                    dataManager.updateUserOnProperty(rejected,type,'notified',true);
                });
            }
        });
    }
};
Example #16
0
  debug('reseting options')
  const optionsOpt = {
    hostname: 'www.nextflick.net',
    method: 'POST',
    path: '/api/resetoptions'
  }
  const optionscallback = function (r) {
    r.on('data', function (data) {
      debug('finished reseting options')
      debug('caching posters')
      const options = {
        hostname: 'www.nextflick.net',
        method: 'POST',
        path: '/api/initiatecache'
      }
      const callback = function (response) {
        response.on('data', function (data) {
          debug('finished caching')
        })
      }
      http.request(options, callback).end()
    })
  }

  http.request(optionsOpt, optionscallback).end()
}
init()
schedule.scheduleJob('*/30 * * * *', function () {
  init()
})
const config = require('../config')
	, Schedule = require('mongoose').model('Schedule')
	, cron = require('node-schedule')
	, yandexMoney = require('./yandexMoney')
	, TelegramBot = require('node-telegram-bot-api')
	, bot = new TelegramBot(config.telegramAPI.token, { polling: false });
    
cron.scheduleJob('0 22 * * *', function () {
    console.info(`Cron started.`);
	Schedule.find({}, function (err, users) {
		if (err) console.error(err);
		users.forEach(function (user) {
			var userId = user.userId;
			yandexMoney.updateIntentions(userId, function (err, message) {
				if (err) return console.error(err);
				bot.sendMessage(userId, message);
			});
		});
	});
});
Example #18
0
const bodyParser = require('body-parser');
const express = require('express'),
      app = express();
const schedule = require("node-schedule");

const { sendDaily } = require("./daily.js");
const { HandleInput } = require("./HandleInput.js")

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/message', (req, res) => {
  HandleInput(req.body.Body);
  res.set('Content-Type', 'text/xml');
  res.status(200);
});

var j = schedule.scheduleJob({hour: 23, minute: 24 }, function(){
  sendDaily()
  console.log("It is time");
});

console.log("RUNIN");
app.listen(process.env.PORT || 3000,() => console.log("express server started at port 3000"));
                if (err) {
                  console.log('err', err);
                  return err;
                }
              });
            }
          }
        }
      });
    });
}

var j = schedule.scheduleJob({
  dayOfWeek: 0,
  hour: 6,
  minute: 30
}, function() {
  logger.info('+recurrentTask: scheduled task : ' + new Date());
  createTaskFromRecurrent(new Date());
});


// Get list of recurrentTasks
exports.index = function(req, res) {
  var myFilter = (req.query.status) ? {
    $or: [{
      'metrics.status': 'Not Started'
    }, {
      'metrics.status': 'In Progress'
    }]
  } : {};
Example #20
0
	},
};

if (!Rooms.global.lotteryDraw) {
	Rooms.global.lotteryDraw = schedule.scheduleJob('0 18 * * 0,3', function () {
		if (lottery.length < 1) return;
		let winner = lottery[Math.floor(Math.random() * lottery.length)];
		let amount = (lottery.length * prices['ticket']) - Math.ceil((lottery.length * prices['ticket']) * 0.10);
		if (amount === 0) amount = 1;
		Economy.writeMoney(winner, amount, function () {
			Economy.logTransaction(winner + " has won " + amount + (amount === 1 ? " buck" : " bucks") + " from the lottery.");
			if (Users(winner) && Users(winner).connected) {
				Users(winner).send("|popup||modal|Congratulations, you have won " + amount + (amount === 1 ? " buck" : " bucks") + " from the lottery.");
			} else {
				if (!Wisp.tells[winner]) Wisp.tells[winner] = {};
				if (!Wisp.tells[winner]['server']) Wisp.tells[winner]['server'] = [];
				Wisp.tells[winner]['server'].push('<span style = "color:gray;"><i>(Sent by the Server on ' + moment().format("ddd, MMMM DD, YYYY HH:mmA ZZ") + ')</i></span><br />' +
				'Congratulations, you have won ' + amount + (amount === 1 ? ' buck' : ' bucks') + ' from the lottery.');
			}
			for (let u in Rooms.global.users) {
				if (!Users(u) || !Users(u).connected) continue;
				Users(u).send("|pm|~Lottery|~|/html Congratulations to " + Wisp.nameColor(winner, true) + " for winning todays lottery. They have won " + amount + " " + (amount === 1 ? "buck." : "bucks."));
			}
			lottery = [];
			fs.writeFileSync('config/lottery.csv', '');
		});
	});
}

exports.commands = {
	lottery: function (target, room, user) {
Example #21
0
         self.routes['/api/tbr']= function(req, res){


            twitterHandles= ['gigaom', 'techcrunch'];

            res.setHeader('Content-Type', 'text/html');
            if(typeof req.query.interval == "undefined"){
                var interval = 1;
            }
            else{
                var interval= parseInt(req.query.interval);
            }

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

            var rule = new schedule.RecurrenceRule();

            rule.minute = new schedule.Range(0, 59, interval);


            var k = schedule.scheduleJob(rule, function(){
                       

                    console.log('starting timer');
                    //dbv.close();



/*

 MongoClient.connect('mongodb://'+connection_string, function(err, db) {

    
    
    dbv=db;
     //console.log(dbv)
    })



MongoClient1 = require('mongodb').MongoClient;


 MongoClient1.connect('mongodb://'+connection_string, function(err, db) {

    
    apiDB=db;
     //console.log(dbv)

     //console.log(apiDB)
    })
*/
                       



            twitter = require('twitter');

                crafter="sarahperk03";
                crafterKeyword = "fitness";
                var twit1 = new twitter({
                consumer_key: 'qBbEAUaLM76o51cjiGq1V8oAY',
                consumer_secret: 'ehgkjRRJQmYhGJRZUgTgNIc4eDET0dzC6hZEX1VnWZeMxZWvXz',
                access_token_key: '2687977814-5c96bGCFymL6Yo2cpB5J40hGeIPyWBk2W4y7zRn',
                access_token_secret: '8ilaJI6LeNp2OsmH51yw4uQlq2urdvhaghl4eIW9OOQ01'
            });




                //users

/*
                connie1 = {"username":"******", 'category':'fashion', 'key':'lKnDiCEadgMuP6iNSm4dJW0vg', 'secret':'DEytPBHrbUfadI6uuDIBXoziEUl7Ze6yFG17TBYVdsX4JufpvA', 'token':'2693910547-AKH80ztv6A1ULMFxtPdtYhXBYo6JbUgvjkthSaD', 'tokensecret':'1sHKnMtH1fNkCrLdfCt7vavGxx2alQEEtqvqwOeUc309A'}
                connieSearch = "from:beautyblitz, OR from:CathyHorynNYT, OR from:glambr, OR from:styledotcom, OR from:vanityfair, OR from:StyleCaster, OR from:fashgonerogue, OR from:popsugarbeauty"
*/

        twitterObjs =
            [
                [{"username":"******", 'category':'fashion', 'key':'Cxhp6whvvXPIIsw7L5OK4tMbH', 'secret':'Fq1LmYij4490z5cJ6ExM16Q5fAhBWC7KMndu70G5ur8lIHkPpY', 'token':'2688197214-DA6imGpQUPNUVIRiWaop3hE0F1q6galbmn4gCcc', 'tokensecret':'ZL0FAzPLSxuYwc8QAAhtlx0daVGSBQX3erywO0sVAmhHT', 'password':"******"}
                ,"from:beautyblitz, OR from:CathyHorynNYT, OR from:glambr, OR from:styledotcom, OR from:vanityfair, OR from:StyleCaster, OR from:fashgonerogue, OR from:popsugarbeauty, OR from:Fashionista_com, OR from:bevysmith, OR from:ManRepeller, OR from:GypsyGagaloo, OR from:ELLEmagazine, OR from:wmag, OR from:BazaarUK, OR from:Chelsea_Fagan, OR from:DressingCute, OR from:LaurenPope, OR from:Dazed_Fashion, OR from:sugarscape, OR from:IndyFashion"],

                  [{"username":"******", 'category':'fitness', 'key':'E6lIu13MvjiVW3V315E6oeG6C', 'secret':'QWd27hVsHRj3kRJsFWhWhrAgcz6jRUXveYtPOGiCjVG9gf25xg', 'token':'2688233732-Lqvd41F8STLT5HlXceJk6zQxToLgVm6Tcr7BGuK', 'tokensecret':'UE8qdGt6GFxHKvldZ5gP7bLUaRHPli68ikV9w4km6zacp', 'password':"******"}
                ,"from:greatist, OR from:dailyburn, OR from:FitBottomedGirl, OR from:TFerriss, OR from:bornfitness, OR from:ElephantJournal, OR from:AthleticFoodie, OR from:zentofitness, OR from:lululemon, OR from:yogadork, OR from:muscle_fitness, OR from:BornFitness, OR from:phillymag, OR from:FitDaiIy, OR from:HealthyLiving, OR from:Shape_Magazine, OR from:Herbalife, OR from:milieu_magazine, OR from:WomensHealthMag, OR from:hellomagazine, OR from:Stay_Fitness, OR from:humanatease, OR from:SELFmagazine"],


                [{"username":"******", 'category':'fitness', 'key':'zTrG0GTRDAeZYv6rXA0JiENZw', 'secret':'khA9bMIeMSMG61p41qhqv9glqC7eczmvqeTsFe72ISjwt8rTO2', 'token':'2688188420-y80CFkE9wONkvtROCXyEcmdeFGUgaoMR5RDCAni', 'tokensecret':'M85Jsopw5vz5yAdfGvh0qaMNnyNuXiELVpLWcgtaarE9z'}
                ,"from:RobbWolf, OR from:trinkfitness, OR from:martinberkhan, OR from:JasonFerruggia, OR from:erwan_le_corre, OR from:johnromaniello, OR from:stevekamb, OR from:iRunnerBlog, OR from:profspiker, OR from:TaraStiles, OR from:dailyburn, OR from:Herbalife, OR from:PreventionMag, OR from:jenberlingo, OR from:POPSUGARFitness, OR from:CelebsVibes, OR from:FairwayMarket, OR from:toworkorplay, OR from:DailyMonitor, OR from:IQuitSugar, OR from:MayoClinic, OR from:EverydayHealth"],
                
                
            ]

            twitterTimer = 5000;
            userCounter=0;
            for(z in twitterObjs){

                 setTimeout(function(){
                    
                  console.log('starting another user '+ twitterObjs[userCounter][0]['username']);

                  //twitterObj[1] is term on twitter to search and [0] is twitter user credentials
                      tweetScale(twitterObjs[userCounter][1], twitterObjs[userCounter][0]);
                      userCounter= userCounter+1;

                }, twitterTimer);

                 twitterTimer = twitterTimer+10000;
            }
               
            












//end timers
                       
            });


              

  res.send("scheduled ");

    };
Example #22
0
    });
}

// Gets all usernames of players in the given room
var players_in_room = function(room) {
    return sockets_in_room(room).map(function(id) {
        return {'name' : current_users[id].username,
                'color' : current_users[id].color};
    });
}

// Cleanse all rooms that are empty every 12 hours
var cleanse = schedule.scheduleJob('0 0 12 * * *', function() {
    for (var room in current_games) {
        if(players_in_room(room).length == 0) {
            var index = current_games.indexOf(room);
            delete players_in_room[index];
        }
    }
});

exports.current_hash = current_hash;
exports.game_exists = game_exists;
exports.add_user = add_user;
exports.remove_user = remove_user;
exports.players_in_room = players_in_room;
exports.cleanse = cleanse;

exports.current_games = current_games;
exports.current_users = current_users;
Example #23
0
var http = require('http');
var schedule = require('node-schedule');
var spider = require('./lib/spider.js');

function serverCallback(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}

// start http server
var server = http.createServer(serverCallback);
server.listen(8080, '0.0.0.0');

// schedule spider job
var rule = new schedule.RecurrenceRule();
rule.hour = 10;
rule.minute = 0;
var job = schedule.scheduleJob(rule, function() {
  spider.run([]);
});
Example #24
0
ruleExteriorOff.minute = 0;

// interior on
var ruleInteriorOn = new schedule.RecurrenceRule();
ruleInteriorOn.hour = 0;
ruleInteriorOn.minute = 1;
ruleInteriorOn.dayOfWeek = 1;

// interior off
var ruleInteriorOff = new schedule.RecurrenceRule();
ruleInteriorOff.hour = 23;
ruleInteriorOff.minute = 59;
ruleInteriorOff.dayOfWeek = 5;

var jobExteriorOn = schedule.scheduleJob(ruleExteriorOn, function() {
  exteriorLtsOn();
  console.log("Turning exterior lights on...");
});
var jobExteriorOff = schedule.scheduleJob(ruleExteriorOff, function() {
  exteriorLtsOff();
  console.log("Turning exterior lights off...");
});
var jobInteriorOn = schedule.scheduleJob(ruleInteriorOn, function() {
  interiorLtsOn();
  console.log("Turning interior lights on...");
});
var jobInteriorOff = schedule.scheduleJob(ruleInteriorOff, function() {
  interiorLtsOff();
  console.log("Turning interior lights off...");
});
Example #25
0
var express = require('express');
var app = express();
var fs = require('fs');
var schedule = require('node-schedule');

schedule.scheduleJob('0 0 * * *', function(){
  console.log('Running plugin updater...');
  try {
  require('./grunt-plugins').download();
  } catch (e) {
    console.log(e);
  }
});

// enable express strict routing, see http://expressjs.com/api.html#app-settings
// for more info
app.enable('strict routing');

/**
 * express app configuration
 */
app.configure(function () {
  app.use(express.methodOverride());
  app.use(express.bodyParser());

  // strip slashes
  app.use(function (req, res, next) {
    if (req.url.substr(-1) === '/' && req.url.length > 1) {
      res.redirect(301, req.url.slice(0, -1));
    } else {
      next();
Example #26
0
        assert.equal(null, error);
        assert(result);
        assert.equal(hoursOfHistory, result.length);
        viewcountdata.viewcounts = result;
        //send to specific socket or send to all?
        if(clientsocket)
            clientsocket.emit('viewupdates', viewcountdata);
        else
            io.sockets.emit('viewupdates', viewcountdata);
    };

    //helper function for asynchronously querying the db for each timestamp range.
    //TBD: would one huge range for 24 hours with sort in client perform better?
    var getViewCount = function(timestamp, callback)
    {
        viewlogsCollection.find({'time' : {$gte: timestamp.start, $lte: timestamp.end}}).toArray(function(err, documents)
        {
            callback(null,documents.length);
        });
    };

    //for each time range, get the view count. then send the results to the server
    async.map(timeRanges, getViewCount, sendViewCountsToClients);
}
//once every hour (at :00 minutes), we need to update the view counts and labels
var schedulerjob = scheduler.scheduleJob({minute: 0}, function()
{
    console.log("an hour has passed, update clients with new labels");
    SendViewCountToClients();
});
Example #27
0
const config = require('./lib/config');
const logger = config.getLogger();
const appConfig = require('./lib/config-app');
const db = require('./lib/mongoose');
const build = require('./lib/build');
const save = require('./lib/save');
const filter = require('./lib/filter');

// schedule for links every 5 minutes
schedule.scheduleJob('*/5 * * * *', function(){
    request(appConfig.pinboard).then(function (resp) {
        return JSON.parse(resp).posts;
    }).then(function(content) {
        content.forEach(function(item) {
            save.saveNew(db.Links, build.schemaLinks(db.Links, item), item.hash);
        });
    }).catch(function (err) {
        logger.error('Pinboard:', err.message);
    });
});
// schedule for photos every 0 and 30th minute past the 0, 3, 6, 9, 12, 15, 18 and 21st hour.
schedule.scheduleJob('*/30 */3 * * *', function(){
    request(appConfig.instagram).then(function (resp) {
        return JSON.parse(resp).data;
    }).then(function(content) {
        return (filter.filterByTag(content, 'coffeeoftheday'));
    }).then(function(filteredContent) {
        filteredContent.forEach(function(item) {
            save.saveNew(db.Coffee, build.schemaCoffee(db.Coffee, item), item.id);
        });
Example #28
0
		}
	})
*/

/*******************************************************
********************************************************/

var schedule = require('node-schedule');
var rule2 = new schedule.RecurrenceRule();
rule2.dayOfWeek = [0, new schedule.Range(0, 6)];
rule2.hour = 1;
rule2.minute = 34;

var j = schedule.scheduleJob(rule2, function(){
    console.log('running the event analytics rule!'.red);
	catalogUpdater.updateMeetingRoomAndLocation();
	catalogUpdater.updateHomeCatalog();
});


/***************************************
****************************************/
//saveResourceList();
function saveResourceList(){
    var redisClient;
    var redis_ip= config.redis.host;  
    var redis_port= config.redis.port; 	
    try{ 
        redisClient = redis.createClient(redis_port,redis_ip);
	}
    catch (error){
Example #29
0
var schedule = require('node-schedule')
var fs = require('fs')
var xlsx = require('node-xlsx')
var Email = require('./email')
var config = require('./config')
var excel = require('./ex-excel')
var tools = require('./tools')
var content = require('./report_content')

console.log('start auto send email task')
var j = schedule.scheduleJob('05 17 * * 7', function() {
  var todayDate = tools.getTodayDate()
  var todayDateString = todayDate + ''
  if (content[todayDateString]) {
    sendEmail()
  } else {
    notify()
  }
})

var sendEmail = function() {
  console.log(new Date() + ' before send an email, your first output an excel file as your attachment')
  generateExcel()
  console.log(new Date() + ' its time to send a email')
  send()
}
var generateExcel = function() {
  excel.exExcel()
}
var notify = function() {
  var data = ''
Example #30
0
scheduler.scheduleJob('0 * * * *', function () {
    var anonim_power = 0;
    AnonymousStatistic.count({}, function (err, count) {
        if (err) {
            return;
        }
        anonim_power = count;
    });
    User.find({}, function (err, users) {
        var exec_count = 0;
        var active_users = 0;
        var banned_users = 0;
        var registered_users = 0;
        var trial_finished = 0;
        var supported_users = 0;
        var statistics = {"data": [], "labels": [], "colors": []};
        var local_statistics = {};
        var colors = ['Red', 'Green', 'Blue', 'Brown', 'Orange', 'Yellow', 'Gray'];

        if (err) {
            console.error("Statistic error: ", err);
        } else {
            users.forEach(function (user) {
                var app_state = user.application_state;
                if (app_state === ApplicationState.ACTIVE) {
                    active_users += 1;
                } else if (app_state === ApplicationState.BANNED) {
                    banned_users += 1;
                } else if (app_state === ApplicationState.TRIAL_FINISHED) {
                    trial_finished += 1;
                }

                if (user.subscription || user.isPrimary()) {
                    supported_users += 1;
                }
                registered_users += 1;

                // statistics
                for (var i = 0; i < user.statistic.length; ++i) {
                    var stat = user.statistic[i];
                    if (!local_statistics.hasOwnProperty(stat.os.name)) {
                        local_statistics[stat.os.name] = 0;
                    }
                    local_statistics[stat.os.name] += 1;
                    exec_count += 1;
                }
            });
        }


        for (var key in local_statistics) {
            var value = local_statistics[key];
            statistics.data.push(value);
            statistics.labels.push('"' + key + '"');
            statistics.colors.push('"' + colors[statistics.data.length - 1] + '"');
        }

        stat = {
            "exec_count": exec_count,
            "registered_users": registered_users,
            "active_users": active_users,
            "banned_users": banned_users,
            "supported_users": supported_users,
            "statistics": statistics,
            "anonim_power": anonim_power
        };
    });
});