Execute code when file is modified

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]];
    task = CreateScheduledTask[If[updatedQ, Print["Changed"], ## &[]], {2, ∞}];
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.

You can start and stop your task with the following commands

StartScheduledTask[Kale`task];
StopScheduledTask[Kale`task];

respectively or remove it altogether using RemoveScheduledTask[Kale`task];.


rm -rf's answer (above) works in Mathematica 12.0 if you replace lastModified = {}; with lastModified =FileDate[fileName, "Modification"]


Dynamic[x]

.

Begin["Kale`"];

myCode[data_] := Style[ListLinePlot[Flatten[data], PlotTheme -> "Marketing"], Magnification -> 2];
fileName = NotebookDirectory[] <> "file.txt";

lastModified = FileDate[fileName, "Modification"];

updatedQ := With[{modificationDate = FileDate[fileName,"Modification"]}, 
   If[lastModified == modificationDate, False, 
    lastModified = modificationDate; True]];

task = CreateScheduledTask[
                 If[
                    updatedQ
    , (
     data = Import[fileName, "Table"]; x = myCode[data]
      )
    , ## &[]
                  ]
                  , {0.1, ∞}
             ];

End[];

.

StartScheduledTask[Kale`task]

enter image description here


note:

in this example, file.txt was created with:

Export[NotebookDirectory[]<>"file.txt",{1,2,3}]//SystemOpen