Immediately delete managed files I have a use case (in D8) where file and corresponding directory needs to be deleted from the file system. The standard mechanism suggested by Drupal is to mark file as temporary and let cron take care of deletion. This means, in my case, that I need to keep track of the file deletion and only then delete the corresponding directory, if it empty. This can be easily avoided by simply using file_delete().

Why is this method not recommended?

The standard cron based deferred deletion causes other side effects with file replacement, etc.
Why is this method not recommended?


The function comments do give a nod to the reason:


  Instead of directly deleting a file, it is strongly recommended to delete file usages instead. That will automatically mark the file as temporary and remove it during cleanup.


But perhaps the "file usage" part of that could have been expanded upon, if you're not aware there's proper reference tracking going on it could be confusing...

Put simply, multiple entities/things can reference a single file. Those references are stored as file usage records, which are consulted when the system wants to know if it's safe to delete a file. If a record exists, for the target file, it can't be deleted without breaking a link, so the system doesn't do it.

Rather than go through that process of checking usage then deleting every time a file is dereferenced, the system batches it up on a cron job for convenience.

If it's not convenient for your use case, and you are comfortable that the file delete is 'safe' with the above in mind, then you can happily ignore the recommendation and use file_delete directly.

If you do, make sure you clear up the file usage records at the same time, or you might end up with inconsistent data some time down the line.