node.js运行js_如何使用Node.js创建和运行计划的作业

node.js运行js

介绍 (Introduction)

Ever wanted to do specific things on your application server at certain times without having to manually run them yourself? This is where scheduled tasks come in handy.

是否曾经想过在特定时间在应用程序服务器上执行特定操作而不必自己手动运行它们? 这是计划任务派上用场的地方。

In this article, you'l create scheduled tasks in Node applications using the node-cron module. You’ll schedule the execution of different scripts at different intervals from your application.

在本文中,您将使用node-cron模块在Node应用程序中创建计划任务。 您将在应用程序中以不同的时间间隔安排执行不同的脚本。

In this tutorial you’ll build a small application that automatically deletes auto-generated log files from the server. Then you’ll look at a few additional use cases.

在本教程中,您将构建一个小型应用程序,该应用程序会自动从服务器删除自动生成的日志文件。 然后,您将看一些其他用例。

先决条件 (Prerequisites)

To follow through this tutorial, you’ll need:

要完成本教程,您需要:

步骤1 –创建节点应用程序并安装依赖项 (Step 1 – Creating A Node Application and Installing Dependencies)

To get started, create a new Node application by opening your terminal and creating a new folder for your project.

首先,通过打开终端并为项目创建一个新文件夹来创建一个新的Node应用程序。

  • mkdir cron-jobs-node && cd cron-jobs-node

    mkdir cron-jobs-node && cd cron-jobs-node

Then initialize it, which creates a package.json file which you’ll use to track dependencies:

然后对其进行初始化,这将创建一个package.json文件,您将使用该文件来跟踪依赖关系:

  • npm init -y

    npm初始化-y

Add the express web framework as a dependency, as well as the node-cron and the fs modules by running the following command:

通过运行以下命令,将express Web框架以及node-cronfs模块添加为依赖项:

  • npm install express node-cron fs

    npm install express节点cron fs

The express module powers the web server you’ll build. node-cron is the task scheduler, and fs is the Node file system module.

express模块为您要构建的Web服务器提供动力。 node-cron是任务计划程序, fs是Node文件系统模块。

The dependencies are installed; let’s build the server.

依赖项已安装; 让我们来构建服务器。

第2步–构建后端服务器 (Step 2 – Building the Backend Server)

Create an index.js file and then import the necessary node modules:

创建一个index.js文件,然后导入必要的节点模块:

  • nano index.js

    纳米index.js

Add this code to index.js to include node-cron and express and create an instance of Express:

将此代码添加到index.js以包括node-cronexpress并创建Express的实例:

index.js
index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");

app = express();

This application will generate logs, and after a while, you’ll want to delete the error log files at intervals automatically. You’ll use node-cron to do this.

该应用程序将生成日志,过一会儿,您将需要定期删除错误日志文件。 您将使用node-cron执行此操作。

To see how this module works, add the following to your index.js file which displays a message every minute:

要查看此模块的工作原理,请将以下内容添加到index.js文件中,该文件每分钟都会显示一条消息:

index.js
index.js
// schedule tasks to be run on the server   
    cron.schedule("* * * * *", function() {
      console.log("running a task every minute");
    });

    app.listen(3128);

Now, when you run the server, we get the following result:

现在,当您运行服务器时,我们得到以下结果:

  • node index.js

    节点index.js

   
   
Output
running a task every minute running a task every minute

You have a task running every minute. Stop the server with CTRL+C.

您有每分钟运行的任务。 使用CTRL+C停止服务器。

Now let’s look at how to run tasks in more detail.

现在,让我们详细了解如何运行任务。

步骤2 –以不同的时间间隔安排任务 (Step 2 – Scheduling Tasks at Different intervals)

With node-cron, you can schedule tasks for different intervals.

使用node-cron ,您可以按不同的时间间隔计划任务。

In the previous example, you created a job that ran every minute by passing * * * * * to the schedule function. Each of those asterisks has a special meaning:

在上一个示例中,您通过将* * * * *传递给schedule函数来创建了每分钟运行的作业。 每个星号都有特殊含义:

* * * * * *
     | | | | | |
     | | | | | day of week
     | | | | month
     | | | day of month
     | | hour
     | minute
     second ( optional )

Learn more about how this notation works in How To Use Cron to Automate Tasks on a VPS.

如何使用Cron在VPS上自动执行任务中了解有关此表示法工作原理的更多信息。

To delete the log file from the server on the 21st of every month, update the index.js to look like this:

要在每月的21日从服务器上删除日志文件,请更新index.js如下所示:

index.js
index.js
// schedule tasks to be run on the server
    cron.schedule("* * 21 * *", function() {
      console.log("---------------------");
      console.log("Running Cron Job");
      fs.unlink("./error.log", err => {
        if (err) throw err;
        console.log("Error file successfully deleted");
      });
    });

    app.listen("3128");

Now, when the server is run, you’ll get the following output on the 21st of the month:

现在,当服务器运行时,您将在每月的21日获得以下输出:

To simulate this yourself, change the scheduler to run in a shorter interval.

若要自己模拟,请更改调度程序以使其在较短的时间间隔内运行。

You can run any actions inside the scheduler. Actions ranging from creating a file, to sending emails and running scripts. Let’s take a look at more use cases

您可以在调度程序中运行任何操作。 从创建文件到发送电子邮件和运行脚本的各种动作。 让我们看一下更多的用例

用例:备份数据库 (Use Case: Backing Up Databases)

Ensuring the accessibility of user data is very key to any business. If an unforeseen event happens and your database becomes corrupted or damaged, you’ll need to restore your database from a backup. You’ll be in serious trouble if you don’t have any form of existing backup for your business. You can use what you’ve learned so far to periodically backup the existing data in your database. Let’s take a look at how to do this. In this example, you’ll use the SQLite database, as it’s less complex than other options and works in the context of this example.

确保用户数据的可访问性对于任何企业都是至关重要的。 如果发生了不可预见的事件,并且数据库已损坏或损坏,则需要从备份中还原数据库。 如果您的企业没有任何形式的现有备份,则会遇到严重的麻烦。 您可以使用到目前为止所学的知识定期备份数据库中的现有数据。 让我们看看如何执行此操作。 在此示例中,您将使用SQLite数据库,因为它不像其他选项那样复杂,并且可以在此示例的上下文中使用。

Visit the SQLite3 download page to download SQlite3 for your platform. You can also install SQlite3 on Ubuntu with the following commands:

访问SQLite3下载页面以为您的平台下载SQlite3。 您还可以使用以下命令在Ubuntu上安装SQlite3:

  • sudo apt-get update

    sudo apt-get更新
  • sudo apt-get install sqlite3 libsqlite3-dev

    须藤apt-get install sqlite3 libsqlite3-dev

Next, install a Node module that lets your app run shell scripts:

接下来,安装一个Node模块,该模块可以让您的应用运行Shell脚本:

You’ll use this library to execute a command that exports your data.

您将使用此库来执行导出数据的命令。

Now create a sample database by running the command:

现在,通过运行以下命令来创建示例数据库:

  • sqlite3 database.sqlite

    sqlite3 database.sqlite

To backup your database at 11:59pm every day, update your index.js file to look like this:

要每天在晚上11:59备份数据库,请更新index.js文件,使其如下所示:

index.js
index.js
const fs = require("fs");
    let shell = require("shelljs");
    const express = require("express");

    app = express();

    // To backup a database
    cron.schedule("59 23 * * *", function() {
      console.log("---------------------");
      console.log("Running Cron Job");
      if (shell.exec("sqlite3 database.sqlite  .dump > data_dump.sql").code !== 0) {
        shell.exit(1);
      }
      else{
        shell.echo("Database backup complete");
      }
    });
    app.listen("3128");

Save the file and run your server:

保存文件并运行服务器:

  • node index.js

    节点index.js

You’ll see the following results:

您会看到以下结果:

Next, let’s look at sending periodic emails.

接下来,让我们看一下定期发送电子邮件。

用例:发送计划的电子邮件 (Use Case: Sending Scheduled Emails)

You can also use jobs to keep your users up to date by sending them emails at different intervals. For example, you can curate a list of interesting links and then send them to users every Sunday. To do this, use the nodemailer module and connect it to your SMTP server, like GMail.

您还可以使用作业,以不同的时间间隔向用户发送电子邮件,以使用户保持最新状态。 例如,您可以策划一个有趣的链接列表,然后在每个星期日将它们发送给用户。 为此,请使用nodemailer模块并将其连接到SMTP服务器(例如GMail)。

Install nodemailer by running the command:

通过运行以下命令来安装nodemailer:

  • npm install --save nodemailer

    npm install-保存nodemailer

Once that is done, update the index.js file to add a section that defines the mailer and sets the username and password for a GMail account:

完成此操作后,更新index.js文件以添加定义邮件程序并设置GMail帐户用户名和密码的部分:

index.js
index.js
const cron = require("node-cron");
    const express = require("express");
    let nodemailer = require("nodemailer");

    app = express();

    // create mail transporter
    let transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: "your_email_address@gmail.com",
        pass: "your_password"
      }
    });

Warning: You will need to temporarily allow non-secure sign-in for your Gmail account if you’d like to use it for testing purposes here. For production applications, configure a specific secure Email account and use those credentials.

警告 :如果要在此处进行测试,则需要暂时​​允许Gmail帐户进行非安全登录。 对于生产应用程序,配置一个特定的安全电子邮件帐户并使用这些凭据。

Then add the task to send the messages every Wednesday:

然后添加任务以在每个星期三发送消息:

index.js
index.js
// sending emails at periodic intervals
    cron.schedule("* * * * Wednesday", function(){
      console.log("---------------------");
      console.log("Running Cron Job");
      let mailOptions = {
        from: "COMPANYEMAIL@gmail.com",
        to: "sampleuser@gmail.com",
        subject: `Not a GDPR update ;)`,
        text: `Hi there, this email was automatically sent by us`
      };
      transporter.sendMail(mailOptions, function(error, info) {
        if (error) {
          throw error;
        } else {
          console.log("Email successfully sent!");
        }
      });
    });

    app.listen("3128");

Now, when you run the server using the command node index.js , you get the following result:

现在,当使用命令node index.js运行服务器时,将得到以下结果:

结论 (Conclusion)

In this article, you used node-cron to schedule jobs in your Node.js applications. You can find the code examples for this tutorial in this GitHub repository repository.

在本文中,您使用了node-cron来调度Node.js应用程序中的作业。 您可以在这个GitHub存储库中找到本教程的代码示例。

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-cron-jobs-by-examples

node.js运行js

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值