diff --git a/app/Command/ClearFileCommand.php b/app/Command/ClearFileCommand.php new file mode 100644 index 0000000..5c63a23 --- /dev/null +++ b/app/Command/ClearFileCommand.php @@ -0,0 +1,50 @@ + + * @link https://github.com/gzydong/hyperf-chat + */ + +namespace App\Command; + +use App\Service\SplitUploadService; +use Hyperf\Command\Annotation\Command; +use Hyperf\Command\Command as HyperfCommand; +use Psr\Container\ContainerInterface; + +/** + * @Command + */ +class ClearFileCommand extends HyperfCommand +{ + /** + * @var ContainerInterface + */ + protected $container; + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + + parent::__construct('system:clear-file'); + } + + public function configure() + { + parent::configure(); + $this->setDescription('清除拆分上传的临时文件!'); + } + + public function handle() + { + $this->line('文件清理中...'); + + di()->get(SplitUploadService::class)->clear(); + + $this->info('文件清理完成...'); + } +} diff --git a/app/Service/SplitUploadService.php b/app/Service/SplitUploadService.php index 45c57ce..bae960d 100644 --- a/app/Service/SplitUploadService.php +++ b/app/Service/SplitUploadService.php @@ -141,4 +141,21 @@ class SplitUploadService 'file_size' => $fileInfo->file_size ]; } + + + /** + * 清理超过24小时的临时文件 + */ + public function clear() + { + // 24小时前 + $time = time() - 60 * 60 * 24 * 1; + + FileSplitUpload::where('file_type', 1)->where('upload_at', '<', $time)->select('hash_name')->chunk(100, function ($rows) { + foreach ($rows as $row) { + @di()->get(Filesystem::class)->deleteDir("tmp/{$row->hash_name}"); + @FileSplitUpload::where('hash_name', $row->hash_name)->delete(); + } + }); + } }