A custom module is creating a file in public:// folder, that should reside there only temporary. How can I delete this temporary file in a cron job?


Write a function in a custom module:

* Implements hook_cron().
mymodule_cron() {
  // Get the file id somehow, make this more generic, perhaps use file_scan_directory()?
  $uri = 'public://temporary/myfile.pdf';
  $files = \Drupal::entityTypeManager()
    ->loadByProperties(['uri' => $uri]);
  if (count($files)) {
    foreach ($files as $item) {
| improve this answer | |

Also in drupal, we can delete a file on a cron job via setting the file status=0.

After 6 hours the cron job will delete the files whose status is zero.

     $filename = "myfile.pdf";
     $tmp_file = file_save_data('', 'public://' . $filename);
     $tmp_file->status = 0; // will automatically delete
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.