We often see a need to wait for a file transaction of some sort to be completed before a script continues to deal with the file in question, and the first script below is a more-or-less ‘standard’ way to do it. This Code Exchange topic addresses the problem that arises when an application is so CPU-greedy that the Finder (which is ‘polite’) is not updating the file size even if asked to do so. (The problem arose with a GUI script of Final Cut Pro in which it was necessary to wait for an “Export” to happen, and the first script below didn’t work). The second script below goes straight for the jugular - it asks the system to tell it the file size.
-- Common form that fails if the machine is pressed for time
-- insert this command after the export command
checkStableSize(destinationFilePath) -- change to correct variable name
-- This works with both Files or Folders
-- Add this handler after main script.
-- Handler to delay until a file's size is completely stable.
on checkStableSize(myFile)
set sizeThen to size of (info for myFile)
repeat
-- tell application "Finder" to update myFile -- may be needed
delay 1 -- seconds (set to longer if needed)
set sizeNow to size of (info for myFile)
if sizeNow - sizeThen = 0 then exit repeat
set sizeThen to sizeNow
end repeat
end checkStableSize
To the rescue - ask the system for the answer:
-- insert this command after the cpu-eating command
checkStableSize(myFile) -- change to correct variable name
-- Use in the script after a brief delay to make sure the file is there.
-- Add this handler after main script.
-- Handler to wait until a file is fully loaded.
on checkStableSize(myFile)
set F to "'" & POSIX path of myFile & "'" -- note single quotes - absolutely necessary
set sizeThen to first word of (do shell script "du -d 0 " & F)
repeat
delay 1 -- seconds (set to longer if needed)
set sizeNow to first word of (do shell script "du -d 0 " & F)
if sizeNow - sizeThen = 0 then exit repeat
set sizeThen to sizeNow
end repeat
end checkStableSize