Skip to main content

interoperability - How can I use Dynamic to run a script when a new file is added to a directory?


I have an external program saving files to some directory on my hard disc. I'd like to run a script that imports and runs a script on each file as it is added to the directory. Is there a simple way to do this using Dynamic? Is it necessary to use Refresh?


For example, I'd like to be able to save a series of text files to a directory (with arbitrary names) and then print the contents in near real-time.



Answer



How about using ScheduledTask? This sets up a Monitor button that if pushed, starts monitoring the given directory ($UserBaseDirectory). If you set timeRes to a smaller value, you can get closer to realtime updating. By specifying nb beforehand, one can redirect printing to the actual notebook. The monitor checks if there is any newly added file in the directory, and lists them immediately in the notebook (unless files were removed, as then an empty list is returned). It is easy to put any further script at the indicated part of the code to e.g. check the contents of the new file(s).


files = FileNames["*", "C:\\Users\\Z\\AppData\\Roaming\\Mathematica"];
active = False;
nb = EvaluationNotebook[];

timeRes = .2;

{Button["Monitor", task = RunScheduledTask[
active = True;
old = files;
files = FileNames["*", $UserBaseDirectory];
If[old =!= files,
newFiles = Complement[files, old];
NotebookWrite[nb, {
Cell["New files are:", "Output"],

Cell[BoxData@newFiles, "Output"]}
];
(* Put your code here. This will be evaluated if the contents of
the directory change. *)
],
timeRes], Enabled -> Dynamic@Not@active],
Button["Stop", RemoveScheduledTask@task; active=False, Enabled->Dynamic@active]}

Dynamic[ScheduledTasks[], UpdateInterval -> timeRes]
Dynamic[Column@files, UpdateInterval -> timeRes]

Comments