node cron_Node.js Cron作业示例

本文介绍了如何在Node.js应用中创建和使用Cron作业,以实现自动化的定时任务,如定期删除服务器文件、备份数据库和发送电子邮件。通过示例展示了如何设置不同的任务间隔,以及使用nodemailer发送邮件。
摘要由CSDN通过智能技术生成

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

先决条件 ( 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值