egg 伺服器叢集情況下的定時任務執行操作(2種方式)
阿新 • • 發佈:2018-12-12
第一種做法不是很好 但是可以花很少成本解決定時器多臺伺服器執行的一些問題
disable
:該引數為 false時,定時任務會被啟動。
這樣的話多臺機器上面都會執行,相當於增加了一個開關當執行到改機器主機名和配置主機名相同時
執行定時任務。(如果服務是部署在docker裡 就會不太好使了 因為主機名是會變化的)
官方也提供了一些解決方案
在 agent.js
中繼承 agent.ScheduleStrategy
,然後通過 agent.schedule.use()
註冊即可
// {app_root}/agent.js module.exports = function(agent) { class CustomStrategy extends agent.ScheduleStrategy { start() { agent.notify.subscribe('remote_task', data => { //隨機通知一個 worker 執行任務 this.sendOne(data); }); } } agent.schedule.use('custsom', CustomStrategy); };
然後在schedule目錄檔案下定義
const Subscription = require('egg').Subscription; class ClusterTask extends Subscription { static get schedule() { return { type: 'custom', }; } async subscribe(data) { await data; } }