egg定时任务

一、定时任务官方文档

可以让我们定时的去执行一些操作。比如定时的检测网站是否被篡改,定时的更新缓存、定 时的爬取数据等。

https://eggjs.org/zh-cn/basics/schedule.html

二、cheerio 模块
cheerio nodejs 的抓取页面模块,为服务器特别定制的,快速、灵活、实施的 jQuery

心实现。适合各种 Web 爬虫程序。
通俗的讲:cheerio 模块可以让我们用 jquery 语法来解析爬取的网页数据。 https://www.npmjs.com/package/cheerio

demo:

app/schedule下:

// var k=110;
// module.exports={

//     schedule: {
//         interval: '5s', // 1 分钟间隔
//         type: 'all', // 指定所有的 worker 都需要执行
//     },

//     async task(ctx) {
//         ++k;
//         console.log(k)
//     }
// }






var k=110;
module.exports=(app)=>{
    return{

        schedule: {
            interval: '5s', // 1 分钟间隔
            type: 'all', // 指定所有的 worker 都需要执行,
            // disable:true
        },
    
        async task(ctx) {
            ++k;

            // var result=await ctx.service.news.getNewsList()
            // console.log(result)

            console.log(k)
        }
    }
}
const Subscription = require('egg').Subscription;

var i=0;

class WatchFile extends Subscription{

  // 通过 schedule 属性来设置定时任务的执行间隔等配置

    static get schedule(){

        return{

            interval:'2s',
            type:'all'   //指定所有的 worker(进程)  都需要执行
        }
    }

    async subscribe() {
      //定时任务执行的操作
      ++i;
      console.log(i);

    //   var result=await this.ctx.service.news.getNewsList()
    //   console.log(result)
      
    }


}

//注意
module.exports = WatchFile;

cheerio模块的使用

//cheerio模块的使用

/*
 1、安装cnpm i cheerio --save

 2、引入cheerio模块  
 
 3、加载要解析的内容
    const $ = cheerio.load('

Hello world

') 4、用法 $('title').html() 获取了要匹配的标题的内容 5、获取的汉子是乱码 const $ = cheerio.load('

Hello world

',{decodeEntities: false})
*/ var cheerio=require('cheerio'); module.exports=(app)=>{ return{ schedule: { interval: '5s', // 1 分钟间隔 type: 'all' }, async task(ctx) { //1、抓取网站内容 var url="https://news.baidu.com/"; var result=await ctx.service.spider.requestUrl(url); var htmlData=result.data.toString(); //2、解析数据 //检测网站是否被篡改 检测网站是否挂掉 const $ = cheerio.load(htmlData,{decodeEntities: false}); var title=$('title').html(); if(title!='百度新闻——全球最大的中文新闻平台'){ console.log('网站挂掉了 或者被修改了'); }else{ console.log('正常') } //获取到了hotnews下面所有的a标签的内容 $('.hotnews a').each(function(){ console.log($(this).html()); }) } } }

 

 

你可能感兴趣的:(egg定时任务)