const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var cron = require('node-cron');
class TaskManager{
   constructor(){
     this.taskDic={};
     this.redisClient=system.getObject("util.redisClient");
     this.buildTaskMap();
  }
  async buildTaskMap(){
     var self=this;
     //订阅任务频道
     await this.redisClient.subscribeTask("task",this);
     var taskPath=settings.basepath+"/app/base/db/task/";
     const files=fs.readdirSync(taskPath);
     if(files){
       files.forEach(function(r){
         var classObj=require(taskPath+"/"+r);
         self[classObj.name]=new classObj();
       });
     }
  }
  async addTask(taskClassName,exp){
    (async (tn,ep)=>{
      if(!this.taskDic[tn]){
        this.taskDic[tn]=cron.schedule(ep,()=>{
          this[tn].doTask();
        });
      }
    })(taskClassName,exp);
  }
  async deleteTask(taskClassName){
    if(this.taskDic[taskClassName]){
      this.taskDic[taskClassName].destroy();
      delete this.taskDic[taskClassName];
    }
  }
  async clearlist(){
    var x=await this.redisClient.clearlist("tasklist");
    return x;
  }
  async publish(channel,msg){
    var x=await this.redisClient.publish(channel,msg);
    return  x;
  }
  async newTask(taskstr){
    return  this.redisClient.rpush("tasklist",taskstr);
  }
}
module.exports=TaskManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
//   cm["InitGiftCache"].cacheGlobalVal().then(x=>{
//     console.log(x);
//   });
// });
