简介
cron提供了一种以特定时间间隔重复任务的方法。可能存在需要每天或每周或每月进行的重复性任务,例如记录和执行备份。
在 Node.js 服务器上实现的一种方法cron是使用node-cron模块。这个库使用的语法对于以前在类 Unix 操作系统中crontab使用过的用户来说可能很熟悉。cron
在本文中,我们将使用node-cron定期从服务器中删除日志文件。
第 1 步 - 创建节点应用程序并安装依赖项
首先,通过打开终端并创建一个新文件夹:
mkdir node-cron-example
接下来,切换到新的项目目录:
cd node-cron-example
然后初始化它,这将创建一个package.json文件:
npm init --yes
node-cron通过运行以下命令添加模块:
npm install node-cron@3.0.0
第 2 步 — 创建任务
现在,您可以构建服务器并使用它node-cron来安排每分钟运行的任务。
创建一个新cron-ping.js文件:
vi cron-ping.js
然后,要求node-cron:
cron-ping.js
const cron = require('node-cron');
接下来,将以下代码行添加到cron-ping.js:
cron-ping.js
// ...
// Schedule tasks to be run on the server.
cron.schedule('* * * * *', function() {
console.log('running a task every minute');
});
这些星号是crontab表示不同时间单位的语法的一部分:
* * * * * *
| | | | | |
| | | | | 天或周
| | | | 月
| | | 天或月
| | 时
| 分
秒( optional )
单个星号的行为类似于通配符。这意味着该任务将针对该时间单位的每个实例运行。五个星号 ( '* * * * *') 表示crontab默认每分钟运行一次。
代替星号的数字将被视为该时间单位的值。允许您安排每天和每周或更复杂的任务。 现在,运行脚本:
node cron-ping.js
几分钟后,您将获得以下结果:
Output
running a task every minute
running a task every minute
running a task every minute
...
您每分钟都有一个示例任务运行。CTRL+C您可以使用( )停止服务器CONTROL+C。
现在,让我们更详细地看看如何运行任务。
第 3 步 — 删除错误日志
假设一个场景,需要在每个月的二十一天定期从服务器中删除日志文件。您可以使用node-cron.
创建一个名为的示例日志文件error.log:
vi error.log
然后,添加一条测试消息:
错误日志
This is an example error message that in a log file that will be removed on the twenty-first day of the month.
创建一个新cron-delete.js文件:
nano cron-delete.js
此任务将用于fs文件unlink。将其添加到文件顶部:
cron-delete.js
const cron = require('node-cron');
const fs = require('fs');
接下来,添加以下代码行:
cron-delete.js
// ...
// Remove the error.log file every twenty-first day of the month.
cron.schedule('0 0 21 * *', function() {
console.log('---------------------');
console.log('Running Cron Job');
fs.unlink('./error.log', err => {
if (err) throw err;
console.log('Error file successfully deleted');
});
});
注意模式:0 0 21 * *.
- 它将分钟和小时的值定义为
0和0(“00:00” - 一天的开始)。 - 它将 day 的值定义为
21。 - 它没有定义月份或星期几。
现在,运行脚本:
node cron-delete.js
在本月的二十一天,您将获得以下输出:
Output
---------------------
Running Cron Job
Error file successfully deleted
您可能不想等到本月的二十一天来验证任务是否已执行。您可以修改调度程序以在更短的时间间隔内运行 - 例如每分钟。
检查您的服务器目录。该error.log文件将被删除。
结论
在本文中,学习了如何使用node-cron在 Node.js 服务器上定时作业。还有其他可用的定时任务程序工具。请务必对它们进行评估,以确定哪种工具最适合您的特定项目。