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('<h2 class="title">Hello world</h2>')

4、用法
 
 $('title').html()   獲取了要匹配的標題的內容


5、獲取的漢子是亂碼 


 const $ = cheerio.load('<h2 class="title">Hello world</h2>',{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());
            })



        }
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM