-1

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?

2

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()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  if (count($files)) {
    foreach ($files as $item) {
      file_delete($item->id());
    }
  }
}
0

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
     $tmp_file->save();

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.