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