Waiting for a file operation

We often face situation in which an AppleScript proceeds before a file operation has stopped and errors as a result. Here are a few ways to see if a file is busy (or created yet).


-- Wait for a saved file to exist (good if it is a new file)
-- Matt-Boy
tell application "Finder"
	activate
	repeat while not (exists file (PathToFile & FileName))
		delay 0.5
	end repeat
end tell

-- Wait for the file to be openable (jj)
try
	open for access file x -- if this succeeds, the file is not busy.
	close access result
	exit repeat
on error -- file is busy
	delay 3
end try

-- Wait for the file size to stabilize (or any other property in 'info for')
-- Original form by John Welch
to fileChanged(myFile)
	-- initialize the loop
	set Size_1 to size of (info for myFile) -- get initial size
	delay 3 --wait 3 seconds, or whatever
	set Size_2 to size of (info for myFile) -- get a newer size, perhaps bigger
	-- repeat until sizes match
	repeat while Size_2 ≠ Size_1 -- if they don't equal, loop until they do
		set Size_1 to Size_2 -- new base size
		delay 3 --wait three seconds, or whatever
		set Size_2 to size of (info for myFolder) -- get a newer size
	end repeat -- once the sizes match, the download is done
end fileChanged

-- Use do shell script lsof  (list open files)
set var to false
repeat until var = true
	try
		set the_files to (do shell script "lsof -F n +d " & (quoted form of POSIX path of source_folder))
	on error the_error
		if the_error = "The command exited with a non-zero status." then
			set var to true
			-- do what you were waiting for
		else
			set the_files to the_error
		end if
	end try
	delay 1 -- or whatever
end repeat

More variations welcome.