# Execute code when file is modified

I have a function the takes some time to complete. The function imports data from a .csv, parses it, and plots certain vectors from there. The .csv is constantly being updated from an external program. Ideally, the file size of the .csv would be monitored and when it changes the function is run. Here's what I have so far (assuming the described function is f).

file = "testfile.csv"
Dynamic[
Refresh[
filesize:=FileByteCount[file];
data = Import[file, "CSV"];
f[data],TrackedSymbols:>{filesize},UpdateInterval->5]]


This works, but seems to run f every 5 seconds no matter if the file size has changed or not. This doesn't seem to be very efficient. Also, if I try to use inside DynamicModule it doesn't work at all.

So, what's the best way to monitor and execute code on a file change?

-

The best way to do this would be using scheduled tasks. This way, you have greater flexibility over starting/stopping and quitting the task than with Dynamic. Here's an example:

Begin["Kale"];
fileName = "~/foo.txt";
lastModified = {};
updatedQ := With[{modificationDate = FileDate[fileName, "Modification"]},
If[lastModified == modificationDate, False, lastModified = modificationDate; True]];
End[];


The above will check every 2 seconds to see if your file has been modified. If it has been, then it prints "Changed" (replace it with your custom function) to the messages window and does nothing otherwise.

StartScheduledTask[Kaletask];
StopScheduledTask[Kaletask];

respectively or remove it altogether using RemoveScheduledTask[Kaletask];.
@rm -rf, So, I'm gathering the best way to dynamically plot the data is to use the scheduled task to format the vectors for plotting, set to a variable, and then use Dynamic[Plot[stuffs]]? –  kale Dec 7 '12 at 20:13
@telefunkenvf14, Yeah, data is streaming into it from that aforementioned external program. I agree on the time stamp thing, so I am still relying on FileByteCount. FileHash could be faster though... –  kale Dec 8 '12 at 14:55
@telefunkenvf14, I just checked. FileByteSize is much much faster. –  kale Dec 8 '12 at 16:08