node cron
Ever wanted to do specific things on your application server at certain times without having to physically run them yourself. You want to spend more of your time worrying about productive tasks instead of remembering that you want to move data from one part of the server to another every month. This is where Cron jobs come in.
曾经想在特定时间在应用程序服务器上执行特定操作,而不必亲自运行它们。 您想花费更多的时间来担心生产任务,而不是记住每个月都要将数据从服务器的一部分移到另一部分。 这是Cron工作进来的地方。
In your Node applications, the applications of these are endless as they save. In this article, we’ll look at how to create and use Cron jobs in Node applications. To do this, we’ll make a simple application that automatically deletes auto-generated error.log
files from the server. Another advantage of Cron jobs is that you can schedule the execution of different scripts at different intervals from your application.
在您的Node应用程序中,这些应用程序在保存时无穷无尽。 在本文中,我们将研究如何在Node应用程序中创建和使用Cron作业。 为此,我们将创建一个简单的应用程序,该应用程序会自动从服务器删除自动生成的error.log
文件。 Cron作业的另一个优点是,您可以安排应用程序以不同的时间间隔执行不同的脚本。
![Cron Job Running a task every minute](https://d2mxuefqeaa7sj.cloudfront.net/s_D4F7DA6873808FD377E98B06C1521D14C91F3045C06779BC5E70ECB6CC08E8AE_1527662633884_image.png)
先决条件 ( Prerequisites )
To follow through this tutorial, you’ll need the following:
要完成本教程,您需要以下内容:
- Node installed on your machine 安装在您机器上的节点
- NPM installed on your machine NPM安装在您的计算机上
- Basic knowledge of JavaScript JavaScript的基础知识
入门 ( Getting Started )
To get started, create a new Node application by opening your terminal and creating a new folder for your project. Then initialize it by running the commands:
首先,通过打开终端并为项目创建一个新文件夹来创建一个新的Node应用程序。 然后通过运行以下命令对其进行初始化:
mkdir cron-jobs-node cd cron-jobs-node
npm init -y
安装节点模块 ( Install Node Modules )
To make this application work we are going to need a couple of dependencies. You can install them by running the following commands:
为了使该应用程序正常工作,我们将需要几个依赖项。 您可以通过运行以下命令来安装它们:
npm install express node-cron fs
express
- powers the web server
express
-权力的Web服务器
node-cron
- task scheduler in pure JavaScript for node.js
node-cron
纯JavaScript的Node.js任务计划程序
fs
- node file system module
fs
节点文件系统模块
构建后端服务器 ( Building the backend server )
Create an index.js
file and then import the necessary node modules:
创建一个index.js
文件,然后导入必要的节点模块:
touch index.js
Edit the index.js
file to look like this:
编辑index.js
文件,如下所示:
// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
app = express();
[...]
Now here’s where node-cron
comes in. After a while, we want to delete the error log files at intervals without having to do it physically. We will use node-cron
to do this. Let’s take a look a simple task first. Add the following to your index.js
file:
现在这里是node-cron
出现位置。过了一会儿,我们希望不定期进行删除错误日志文件的操作。 我们将使用node-cron
来做到这一点。 首先让我们看一个简单的任务。 将以下内容添加到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 we run the server, we get the following result:
现在,当我们运行服务器时,将得到以下结果:
> node index.js
running a task every minute
running a task every minute
安排任务的不同间隔 ( Different intervals for scheduling tasks )
With node-cron
, we can schedule tasks for different intervals. Let’s see how to schedule task using different intervals. In the example above, we created a simple Cron job, the parameters passed to the .schedule()
function were * * * * *
. These parameters have different meanings when used:
使用node-cron
,我们可以安排不同时间间隔的任务。 让我们看看如何使用不同的时间间隔安排任务。 在上面的示例中,我们创建了一个简单的Cron作业,传递给.schedule()
函数的参数为* * * * *
。 这些参数在使用时具有不同的含义:
* * * * * *
| | | | | |
| | | | | day of week
| | | | month
| | | day of month
| | hour
| minute
second ( optional )
Using this example, if we want to delete the log file from the server on the 21st of every month, we update the index.js
to look like this:
使用此示例,如果我们想在每月的21日从服务器删除日志文件,我们将index.js
更新为如下所示:
// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
app = express();
// 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 succesfully deleted");
});
});
app.listen("3128");
Now, when the server is run, you get the following output:
现在,当服务器运行时,您将获得以下输出:
![Cron Job automatically deleting error file](https://d2mxuefqeaa7sj.cloudfront.net/s_D4F7DA6873808FD377E98B06C1521D14C91F3045C06779BC5E70ECB6CC08E8AE_1527664313961_image.png)
NB: To simulate the tasks, intervals were set to shorter period by setting the number of minutes in the parameter for the task scheduler
注意:为了模拟任务,通过在任务计划程序的参数中设置分钟数,将间隔设置为较短的时间
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
您可以在调度程序中运行任何操作。 从创建文件到发送电子邮件和运行脚本的各种操作。 让我们看一下更多的用例
用例2-备份数据库 ( Use Case 2 - Backing Up Database )
Ensuring the accessibility of user data is very key to any business. If an unforeseen event happens and your database becomes corrupt, all hell will break loose if you don’t have any form of existing backup for your business. To save yourself the stress in the occurrence of such, you can also use Cron jobs to periodically backup the existing data in your database. Let’s take a look at how to do this.
确保用户数据的可访问性对于任何企业都是至关重要的。 如果发生了不可预见的事件,并且您的数据库损坏了,那么如果您没有任何形式的现有业务备份,那么地狱就会崩溃。 为了避免这种情况的发生,您还可以使用Cron作业定期备份数据库中的现有数据。 让我们看看如何执行此操作。
For the ease of explanation, we are going to use SQLite database
为了便于说明,我们将使用SQLite数据库
First, we need to install a node module that allows us to run shell scripts:
首先,我们需要安装一个节点模块,该模块允许我们运行shell脚本:
npm install shelljs
And also install SQLite if you haven’t:
如果还没有,还安装SQLite:
npm install sqlite3
Now create a sample database by running the command:
现在,通过运行以下命令来创建示例数据库:
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
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");
Now, when you run the server using the command:
现在,当您使用以下命令运行服务器时:
node index.js
You get the following result:
您得到以下结果:
![Server Running a Backup of Database](https://d2mxuefqeaa7sj.cloudfront.net/s_D4F7DA6873808FD377E98B06C1521D14C91F3045C06779BC5E70ECB6CC08E8AE_1527679761487_image.png)
用例3-每隔n次发送电子邮件 ( Use Case 3 - Sending emails every n-time interval )
You can also use Cron jobs to keep your users up to date as to what is going on with your business 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 something like this, you’ll need to do the following.
您还可以使用Cron作业,以不同的时间间隔向他们发送电子邮件,以使您的用户了解企业的最新情况。 例如,您可以策划一个有趣的链接列表,然后在每个星期日将它们发送给用户。 要执行此操作,您需要执行以下操作。
Install nodemailer by running the command:
通过运行以下命令来安装nodemailer:
npm install nodemailer
Once that is done, update the index.js
file to look like this:
完成后,更新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: "COMPANYEMAIL@gmail.com",
pass: "userpass"
}
});
// 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");
NOTE: You will need to temporarily allow non-secure sign-in for your Gmail account for testing purposes here
注意:您将需要暂时允许非安全登录您的Gmail帐户用于测试目的这里
Now, when you run the server using the command node index.js
, you get the following result:
现在,当使用命令node index.js
运行服务器时,将得到以下结果:
![Server Running Cron Job](https://d2mxuefqeaa7sj.cloudfront.net/s_D4F7DA6873808FD377E98B06C1521D14C91F3045C06779BC5E70ECB6CC08E8AE_1527677671376_image.png)
![Email Automatically sent by Cron Job](https://d2mxuefqeaa7sj.cloudfront.net/s_D4F7DA6873808FD377E98B06C1521D14C91F3045C06779BC5E70ECB6CC08E8AE_1527677608568_cron-screenshot.png)
结论 ( Conclusion )
In this article, we have seen an introduction to Cron jobs and how to use them in your Node.js applications. Here’s a link to the GitHub repository. Feel free to add a suggestion or leave a comment below.
在本文中,我们看到了Cron作业的介绍以及如何在Node.js应用程序中使用它们。 这是GitHub存储库的链接。 随时添加建议或在下面发表评论。
翻译自: https://scotch.io/tutorials/nodejs-cron-jobs-by-examples
node cron