能夠讓咱們定時的去執行一些操做。好比定時的檢測網站是否被篡改,定時的更新緩存,定時的爬取數據等。javascript
官網上對定時任務的一些介紹:html
https://eggjs.org/zh-cn/basics/schedule.htmljava
①定時任務的第一種寫法:linux
app>新建schedule(固定寫法)文件夾,在新建watchfile.js(名字隨便起),鍵入如下內容:git
const Subscription = require("egg").Subscription; class WatchFile extends Subscription { // 經過schedule屬性開設置定時任務的執行間隔等配置 static get schedule() { return { interval: "2s", type: "all" // 指定全部的worker(進程)都須要執行 }; } async subscribe() { // 定時任務執行的操做 console.log(new Date()); } } module.exports = WatchFile;
以上可知程序運行後,每隔2s會打印一個當前時間:github
②定時任務的第二種寫法:鍵入以下代碼,可知當程序運行,兩個定時任務都會執行。緩存
var k = 0; module.exports = { schedule: { interval: "5s", type: "all" }, async task(ctx) { k++; console.log(k); } };
③定時任務的第三種寫法。app
var k = 0; module.exports = app => { return { schedule: { interval: "5s", type: "all" }, async task(ctx) { k++; console.log(k); } }; };
④最經常使用的兩個配置:async
經過 schedule.interval
參數來配置定時任務的執行時機,定時任務將會每間隔指定的時間執行一次。interval 能夠配置成網站
5000
。5s
。 module.exports = { schedule: { // 每 10 秒執行一次 interval: '10s', }, }; |
經過 schedule.cron
參數來配置定時任務的執行時機,定時任務將會按照 cron 表達式在特定的時間點執行。cron 表達式經過 cron-parser 進行解析。
注意:cron-parser 支持可選的秒(linux crontab 不支持)。
* * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) │ │ │ │ └───── month (1 - 12) │ │ │ └────────── day of month (1 - 31) │ │ └─────────────── hour (0 - 23) │ └──────────────────── minute (0 - 59) └───────────────────────── second (0 - 59, optional) |
module.exports = { schedule: { // 每三小時準點執行一次 cron: '0 0 */3 * * *', }, }; |
⑤定時任務中能夠訪問ctx對象。
首先在app下新建service文件夾,在新建news.js文件,鍵入以下代碼:返回一些假數據。
// app/service/index.js const Service = require("egg").Service; class NewsService extends Service { async getNewsList() { return [ { title: "紐約州長說防疫物資都來自中國", amount: "483萬" }, { title: "淘寶天貓總裁蔣凡因傳言致歉", amount: "466萬" }, { title: "入境淚崩的留學生作志願者", amount: "450萬" } ]; } } module.exports = NewsService;
而後在定時任務裏面用ctx對象訪問服務當中的方法,打印假數據,可知也能訪問到。
var k = 0; module.exports = app => { return { schedule: { interval: "5s", type: "all" }, async task(ctx) { let newsList = await ctx.service.news.getNewsList(); console.log(newsList); } }; };
⑥,不刪代碼,禁用定時任務。加一個disabled的屬性爲true就好啦。
約定配置真方便,感受eggjs上手有點方便啊。。。起牀次飯。。。