RemoveOldTasksBackgroundJob.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace OC\TaskProcessing;
  3. use OC\TaskProcessing\Db\TaskMapper;
  4. use OCP\AppFramework\Utility\ITimeFactory;
  5. use OCP\BackgroundJob\TimedJob;
  6. use OCP\Files\AppData\IAppDataFactory;
  7. use OCP\Files\NotFoundException;
  8. use OCP\Files\NotPermittedException;
  9. use OCP\Files\SimpleFS\ISimpleFolder;
  10. use Psr\Log\LoggerInterface;
  11. class RemoveOldTasksBackgroundJob extends TimedJob {
  12. public const MAX_TASK_AGE_SECONDS = 60 * 50 * 24 * 7 * 4; // 4 weeks
  13. private \OCP\Files\IAppData $appData;
  14. public function __construct(
  15. ITimeFactory $timeFactory,
  16. private TaskMapper $taskMapper,
  17. private LoggerInterface $logger,
  18. IAppDataFactory $appDataFactory,
  19. ) {
  20. parent::__construct($timeFactory);
  21. $this->setInterval(60 * 60 * 24);
  22. // can be deferred to maintenance window
  23. $this->setTimeSensitivity(TimedJob::TIME_INSENSITIVE);
  24. $this->appData = $appDataFactory->get('core');
  25. }
  26. /**
  27. * @inheritDoc
  28. */
  29. protected function run($argument): void {
  30. try {
  31. $this->taskMapper->deleteOlderThan(self::MAX_TASK_AGE_SECONDS);
  32. } catch (\OCP\DB\Exception $e) {
  33. $this->logger->warning('Failed to delete stale task processing tasks', ['exception' => $e]);
  34. }
  35. try {
  36. $this->clearFilesOlderThan($this->appData->getFolder('text2image'), self::MAX_TASK_AGE_SECONDS);
  37. } catch (NotFoundException $e) {
  38. // noop
  39. }
  40. try {
  41. $this->clearFilesOlderThan($this->appData->getFolder('audio2text'), self::MAX_TASK_AGE_SECONDS);
  42. } catch (NotFoundException $e) {
  43. // noop
  44. }
  45. try {
  46. $this->clearFilesOlderThan($this->appData->getFolder('TaskProcessing'), self::MAX_TASK_AGE_SECONDS);
  47. } catch (NotFoundException $e) {
  48. // noop
  49. }
  50. }
  51. /**
  52. * @param ISimpleFolder $folder
  53. * @param int $ageInSeconds
  54. * @return void
  55. */
  56. private function clearFilesOlderThan(ISimpleFolder $folder, int $ageInSeconds): void {
  57. foreach($folder->getDirectoryListing() as $file) {
  58. if ($file->getMTime() < time() - $ageInSeconds) {
  59. try {
  60. $file->delete();
  61. } catch (NotPermittedException $e) {
  62. $this->logger->warning('Failed to delete a stale task processing file', ['exception' => $e]);
  63. }
  64. }
  65. }
  66. }
  67. }