node.js运行js
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.
在本教程中,您将构建一个小型应用程序,该应用程序会自动从服务器删除自动生成的日志文件。 然后,您将看一些其他用例。
To follow through this tutorial, you’ll need:
要完成本教程,您需要:
A local development environment for Node.js. Follow How to Install Node.js and Create a Local Development Environment
Node.js的本地开发环境。 遵循如何安装Node.js和创建本地开发环境
To get started, create a new Node application by opening your terminal and creating a new folder for your project.
首先,通过打开终端并为项目创建一个新文件夹来创建一个新的Node应用程序。
Then initialize it, which creates a package.json
file which you’ll use to track dependencies:
然后对其进行初始化,这将创建一个package.json
文件,您将使用该文件来跟踪依赖关系:
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-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.
依赖项已安装; 让我们来构建服务器。
Create an index.js
file and then import the necessary node modules:
创建一个index.js
文件,然后导入必要的节点模块:
Add this code to index.js
to include node-cron
and express
and create an instance of Express:
将此代码添加到index.js
以包括node-cron
并express
并创建Express的实例:
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
文件中,该文件每分钟都会显示一条消息:
// 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:
现在,当您运行服务器时,我们得到以下结果:
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.
现在,让我们详细了解如何运行任务。
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
如下所示:
// 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
您可以在调度程序中运行任何操作。 从创建文件到发送电子邮件和运行脚本的各种动作。 让我们看一下更多的用例
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:
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:
现在,通过运行以下命令来创建示例数据库:
To backup your database at 11:59pm every day, update your index.js
file to look like this:
要每天在晚上11:59备份数据库,请更新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:
保存文件并运行服务器:
You’ll see the following results:
您会看到以下结果:
Next, let’s look at sending periodic 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:
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帐户用户名和密码的部分:
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:
然后添加任务以在每个星期三发送消息:
// 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
运行服务器时,将得到以下结果:
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