Egg 中的定時任務

在項目開發中,有許多場景需要執行一些定時任務,Egg 提供了一套機制來讓定時任務的編寫和維護更加優雅。

1. 定時任務的使用場景

1. 定時上報應用狀態。

2. 定時從遠程接口更新本地緩存。

3. 定時進行文件切割、臨時文件刪除。

 

2. 定時任務的寫法

所有定時任務都統一存放在 app/schedule 目錄下,每一個文件都是一個獨立的定時任務,可以配置定時任務的屬性和要執行的方法。

// app/schedule/updateCache.js
const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
    // 通過 schedule 屬性來設置定時任務的執行間隔等配置
    static get schedule() {
        return {
            // 執行時間間隔
            interval: '5s',
            // 指定所有的worker(進程)都需要執行
            type: 'all',
            // 是否禁用
            disable: false
        }
    }
    // 定時執行的操作
    async subscribe() {
        const res = await this.ctx.curl('http://www.api.com/cache', {
            dataType: 'json',
        });
        this.ctx.app.cache = res.data;
    }
}
module.exports = UpdateCache;

定時任務還可以這樣簡寫。

// app/schedule/updateCache.js
module.exports = {
    // 通過 schedule 屬性來設置定時任務的執行間隔等配置
    schedule: {
        // 執行時間間隔
        interval: '5s',
        // 指定所有的worker(進程)都需要執行
        type: 'all',
        // 是否禁用
        disable: false
    },
    // 定時執行的任務
    async task(ctx) {
        const res = await ctx.curl('http://www.api.com/cache', {
            dataType: 'json',
        });
        ctx.app.cache = res.data;
    }
}

有時候我們需要配置定時任務的參數,定時任務還有支持另一種寫法。

// app/schedule/updateCache.js
module.exports = (app) => {
    return {
        // 通過 schedule 屬性來設置定時任務的執行間隔等配置
        schedule: {
            // 執行時間間隔
            interval: '5s',
            // 指定所有的worker(進程)都需要執行
            type: 'all',
            // 是否禁用
            disable: false
        },
        // 定時執行的任務
        async task(ctx) {
            const res = await ctx.curl('http://www.api.com/cache', {
                dataType: 'json',
            });
            ctx.app.cache = res.data;
        }
    }
}

 

3. 定時任務的配置

1. 定時方式

(1). interval

通過 schedule.interval 參數來配置定時任務的執行時機,定時任務將會每間隔指定的時間執行一次,interval 可以配置成:

A. 數字類型,單位爲毫秒數,例如 5000

B. 字符類型,會通過 ms 轉換成毫秒數,例如 5s

module.exports = {
    schedule: {
        // 每 10 秒執行一次
        interval: '10s',
    },
};

(2). cron

通過 schedule.cron 參數來配置定時任務的執行時機,定時任務將會按照 cron 表達式在特定的時間點執行,cron 表達式通過 cron-parser 進行解析。

注意:cron-parser 支持可選的秒( linux crontab 不支持 )

module.exports = {
    schedule: {
        // 每3小時準點執行一次
        cron: '0 0 */3 * * *',
    },
};

2. 執行類型

(1). worker

每臺機器上只有一個 worker 會執行這個定時任務,每次執行定時任務的 worker 的選擇是隨機的。

(2). all

每臺機器上的每個 worker 都會執行這個定時任務。

3. 其它參數

(1). cronOptions

配置 cron 的時區等,參見 cron-parser 文檔。

(2). immediate

配置了該參數爲 true 時,這個定時任務會在應用啓動並 ready 後立刻執行一次這個定時任務。

(3). disable

配置該參數爲 true 時,這個定時任務不會被啓動。

(4). env

數組,僅在指定的環境下才啓動該定時任務。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章