能够让咱们定时的去执行一些操做。好比定时的检测网站是否被篡改,定时的更新缓存,定时的爬取数据等。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上手有点方便啊。。。起床次饭。。。