简体   繁体   English

保持节点js函数运行而无需使用前端的任何调用

[英]keep a node js function running without using any calls from front end

I need to have my NodeJs API to keep creating random data in mongodb. 我需要拥有NodeJs API,才能继续在mongodb中创建随机数据。

I am avoiding calling it from from client-end since this should be something happening completely at back-end. 我避免从客户端调用它,因为这应该完全在后端发生。

var autoCreate = function(){
  var randomNumb = (Math.random()* (10-0) + 0).toFixed(0);
  var randomThing = randomstring.generate({
    length: randomNumb,
    charset: 'alphabetic'
  });

  Thing.create({
    name: randomThing,
    readByUser: false 
  }, function(err, thing) {
    if(err) { return handleError(res, err); }
  });

  setInterval(function() {
    autoCreate();
  }, randomNumb*1000);
}

But how and where do I call this function for the first time. 但是,第一次如何以及在何处调用此函数。 In my Node API file/controller, I can not just write autoCreate() , It breaks. 在我的Node API文件/控制器中,我不能只写autoCreate() ,它会中断。

What would be the right way of doing it> 什么是正确的方法>

As long as there is an active timer, your script will keep on running. 只要有一个活动计时器,您的脚本就会继续运行。

The code in your question has a small flaw, in that it will call setInterval every time the function itself is invoked, but the function itself is never invoked. 您问题中的代码有一个小缺陷,即每次调用函数本身时都会调用setInterval ,但永远不会调用函数本身。 This means it is not started, and if you were to start it, you will keep adding new intervals right up to the point where the process, the database process or the entire system will crash. 这意味着它尚未启动,如果要启动它,则将一直添加新的时间间隔,直到进程,数据库进程或整个系统崩溃为止。

An example using setInterval 使用setInterval的示例

function ping() {
  console.log('ping');
}

setInterval(ping, Math.random() * 1000);

Simply start ping -ing with a random interval (where the random time is generated once and used as the interval between ping s) 只需以随机间隔开始ping -ing(其中随机时间生成一次,并用作ping之间的间隔)

An example using setTimeout (which is what you seem to want) 使用setTimeout的示例(这似乎是您想要的)

function ping() {
  clearTimeout(timer);
  console.log('ping');

  timer = setTimeout(ping, Math.random() * 1000);
}

//  ensure the timer variable exists in the global scope
var timer;
ping();

In this example, you need to start ping -ing yourself and it will just keep invoking itself with random intervals. 在这个例子中,你需要开始ping -ing自己,将只保留随机间隔调用本身。

Use this function to register your autoCreate call 使用此功能注册您的autoCreate调用

setTimeout(autoCreate, 1000);

This will register a call to your autoCreate function every 1 sec. 这将每1秒记录一次对autoCreate函数的调用。

Also make a call to the autoCreate function at the last line of your callback to MongoClient.connect function. 还要在MongoClient.connect函数的回调的最后一行调用autoCreate函数。

You can call after declaration, no client interaction. 您可以在声明后调用,无需客户端交互。

var autoCreate = function(){
    var randomNumb = (Math.random()* (10-0) + 0).toFixed(0);
     var randomThing = randomstring.generate({
    length: randomNumb,
    charset: 'alphabetic'
  });

   Thing.create({
    name: randomThing,
    readByUser: false 
  }, function(err, thing) {
      if(err) { return handleError(res, err); }
    });

   setInterval(function() {
  autoCreate();
  }, randomNumb*1000);

  }

autoCreate(); //Call here 

The best way to automate tasks at backend is to use cron jobs. 在后端自动执行任务的最佳方法是使用cron作业。 Here is a module to the rescue node-cron . 这是救援节点cron的模块。 Here is an example - 这是一个例子-

  var autoCreate = function(){
    var randomNumb = (Math.random()* (10-0) + 0).toFixed(0);
    var randomThing = randomstring.generate({
      length: randomNumb,
      charset: 'alphabetic'
    });

    Thing.create({
      name: randomThing,
      readByUser: false 
    }, function(err, thing) {
      if(err) { return handleError(res, err); }
    });
  }

var CronJob = require('cron').CronJob;
var job = new CronJob('00 30 11 * * 1-5', function() {
  autoCreate();
  /*
   * Runs every weekday (Monday through Friday)
   * at 11:30:00 AM. It does not run on Saturday
   * or Sunday.
   */
  }, function () {
    /* This function is executed when the job stops */
  },
  true, /* Start the job right now */
  timeZone /* Time zone of this job. */
);

You can set the cron pattern according to your need. 您可以根据需要设置cron模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM