# 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.

-
You may find this question related. Also, maybe you can run Mathematica script (which do what you want with that files), with that external program so Mathematica do not have to constantly monitor your directory? If you can, then you can use: automatically run initialization cell –  Kuba Sep 6 '13 at 7:43
@Kuba Unfortunately I can't really modify the outside application placing files in the directory. Also, I read through the question you referenced - coupled with a very high refresh rate, it would be very helpful to have a simple function that returns the chronologically newest file in the directory (i.e. the file with the modified date closest to AbsoluteTime) but surely there must be a simpler way to proceed than the test code linked in the question? –  R.Astare Sep 6 '13 at 8:12

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],