Store a field on a node
Set the status of the created file to something other than PERMANENT.

So replace

$file-&gt;setPermanent();


with

$file-&gt;status = 0;


The file field will then set the status to permanent and add the file_usage metadata.