ClearMessage.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace app\common\task;
  3. use yunwuxin\cron\Task;
  4. use think\Exception;
  5. use think\facade\Db;
  6. use app\manage\model\{Config};
  7. use app\enterprise\model\Message;
  8. // 自动清理消息定时任务
  9. class ClearMessage extends Task
  10. {
  11. // 定时任务日志内容
  12. protected $content='';
  13. protected $path='';
  14. protected $daytime=86400;
  15. /**
  16. * 自动写入定时任务日志
  17. * @return \think\response\Json
  18. */
  19. protected function writeLog($text)
  20. {
  21. $this->path = root_path() . 'crontab.txt';
  22. $content = '重置中!';
  23. if (!file_exists($this->path)) {
  24. fopen($this->path, 'w');
  25. }
  26. if (date('d') != 10) {
  27. $content = file_get_contents($this->path);
  28. }
  29. file_put_contents($this->path, $content . date('Y-m-d H:i:s') . ':' . $text . PHP_EOL);
  30. }
  31. public function configure()
  32. {
  33. //设置每天2点执行
  34. $this->dailyAt('02:00');
  35. }
  36. /**
  37. * 执行任务
  38. * @return mixed
  39. */
  40. protected function execute()
  41. {
  42. if(date('H:i')!='02:00'){
  43. return false;
  44. }
  45. try {
  46. $config=Config::getSystemInfo();
  47. $status=$config['chatInfo']['msgClear'] ?? false;
  48. $days=$config['chatInfo']['msgClearDay'] ?? 0;
  49. if($status && $days){
  50. $time=time() - ($days * $this->daytime);
  51. $where[]=['create_time','<',$time];
  52. $where[]=['chat_identify','<>','admin_notice']; //不删除公告
  53. $where[]=['to_user','<>',-1]; //不删除收藏
  54. $fileIds=Message::where($where)->where([['type','in',['image','video','file']],['file_id','>',0]])->column('file_id');
  55. queuePush(['action'=>'clearFiles','fileIds'=>array_unique($fileIds)],10);
  56. $list=Message::where($where)->where([['type','=','voice']])->column('content');
  57. queuePush(['action'=>'clearVoice','list'=>$list],60);
  58. Message::where($where)->delete();
  59. // 整理数据碎片
  60. $sql="ALTER TABLE `".config('database.connections.mysql.prefix')."message` ENGINE = InnoDB;";
  61. Db::execute($sql);
  62. }
  63. print "****************消息清理成功******************\n";
  64. } catch (Exception $e) {
  65. print '消息清理失败:'.$e->getMessage()."\n";
  66. }
  67. }
  68. }