MATLAB: File Watcher for continuous running program

eventnet

Hello,
I'm trying to write a script that will watch a file system (folder with sub folders) and run a function every time a new file is automatically generated from another system and placed in the watched directory. I also need the script to listen for files that are copied into the watched directory.
I have been playing with the solution here but it only runs once and doesn't continue listening.
once this works, i plan on compiling it as a standalone .exe that will run 24/7 and process new files.
Please let me know what I am missing here to keep it running. Below is what I have so far, it does absolutely nothing when i copy a new file into the directory:
function continual_process()
process = true;
while process
path_to_watch = 'C:\Users\3cal-shape\Desktop\test';
fileObj = System.IO.FileSystemWatcher(path_to_watch);
fileObj.Filter = '*.slm';
fileObj.EnableRaisingEvents = true;
addlistener(fileObj,'Created', @eventhandlerChanged);
addlistener(fileObj,'Changed', @eventhandlerChanged);
end
end
function eventhandlerChanged(source,arg) disp(source) disp('found new file') end

Best Answer

the post that you linked to is using this functionality in a figure, so the callbacks are used as long as the figure is running. The mention of the infinite loop in that post refers to making your script run continuously, not recreating the fileObj repeatedly. In order to do this, remove the while loop and move to after the final addlistener. This will leave the fileObj as it was created, but continue listening as long as the loop is running.
For example:
function continual_process()
path_to_watch = 'C:\Users\3cal-shape\Desktop\test';
fileObj = System.IO.FileSystemWatcher(path_to_watch);
fileObj.Filter = '*.slm';
fileObj.EnableRaisingEvents = true;
addlistener(fileObj,'Created', @eventhandlerChanged);
addlistener(fileObj,'Changed', @eventhandlerChanged);
i=0;
while i<1000000
i = i+1;
pause(0.001);
end
end
function eventhandlerChanged(source,arg)
disp(source)
disp('found new file')
end