1. 程式人生 > 實用技巧 >Node.js實現定時任務

Node.js實現定時任務

我曾經想要在特定時間執行特定的操作,而無需親自執行它們。

在本文中,我們將研究如何在 Node 程式中建立和使用 Cron 作業。為此我們將建立一個簡單的程式,該應用程式會自動從伺服器中刪除自動生成的error.log檔案。 Cron 作業的另一個優點是,你可以安排程式以不同的時間間隔執行不同的指令碼。

前提條件

要繼續學習本教程,你需要具備以下條件:

  • 在你的機器上安裝的 Node
  • 在你的計算機上安裝有npm
  • JavaScript的基礎知識

入門

首先,以下命令併為專案建立一個新的 Node 程式,然後其進行初始化:

mkdir cron-jobs-node cd cron-jobs-node
npm init -y

安裝 Node 模組

為了使程式正常工作,我們將需要幾個依賴項。你可以通過執行以下命令來安裝它們:

npm install express node-cron fs

express- Web 伺服器

node-cron- 用於 node.js的純JavaScript任務計劃程式

fs- 檔案系統模組

構建後端伺服器

建立一個index.js檔案,然後匯入必要的 Node 模組:

touch index.js

編輯index.js檔案,如下所示:

// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");

app = express();

[...]

這是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);
[...]

現在,當我們執行伺服器時將得到以下結果:

> node index.js

running a task every minute
running a task every minute

排程任務的時間間隔

通過node-cron,可以安排不同時間間隔的任務。讓我們看看如何使用不同的時間間隔來安排任務。在上面的示例中,我們建立了一個簡單的 Cron 作業,傳遞給.schedule()函式的引數為 ​​* * * * *。這些引數在使用時具有不同的含義:

* * * * * *
| | | | | |
| | | | | day of week
| | | | month
| | | day of month
| | hour
| minute
second ( optional )

在這個例子中,如果想在每月的 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");

當服務執行時,你將獲得以下輸出:

注意:要模擬本任務,可以通過在引數中設定分鐘數來將間隔設定為較短的時間

你可以在排程程式中執行任何操作。從建立檔案到傳送電子郵件和執行指令碼的各種操作。讓我們看一下更多的用例

用例2 - 備份資料庫

確保使用者資料的可訪問性對於任何企業都是至關重要的。萬一使你的資料庫因為發生意外而受到損壞,如果沒有備份的話,那麼一切將會變得一團糟。為了避免這種情況的發生,你還可以用 Cron 作業定期備份資料庫中的現有資料。讓我們來看看如何做到這一點。

為了便於說明,我們將使用 SQLite 資料庫

首先,我們需要安裝一個 Node 模組,該模組允許我們執行shell指令碼:

npm install shelljs

還要安裝SQLite:

npm install sqlite3

現在,通過執行以下命令來建立示例資料庫:

sqlite3 database.sqlite

想要每天晚上 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");

現在,當你用以下命令執行服務時:

node index.js

將會得到以下結果:

資源搜尋網站大全 https://www.renrenfan.com.cn

用例3 - 每隔 一段時間傳送一次電子郵件

你還可以用 Cron 作業以不同的時間間隔傳送電子郵件,使你的使用者瞭解企業的​​最新情況。例如,你可以策劃一個有趣的連結列表,然後在每個星期日將它們傳送給使用者。要執行此操作,你需要執行以下操作。

通過執行以下命令來安裝 nodemailer:

npm install nodemailer

完成後,更新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: "[email protected]",
        pass: "userpass"
    }
});

// sending emails at periodic intervals
cron.schedule("* * * * Wednesday", function(){
    console.log("---------------------");
    console.log("Running Cron Job");
    let mailOptions = {
        from: "[email protected]",
        to: "[email protected]",
        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");
注意:出於測試目的,你需要暫時允許 Gmail 帳戶進行非安全登入。

現在,當用node index.js執行服務時,將得到以下結果: