Group Abstract Group Abstract

Message Boards Message Boards

1
|
7K Views
|
2 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Running a scheduled task on a file directory to see if files added

Posted 4 years ago

Is there anyway to run scheduled task on directory at a certain time interval to see for file additions? The below code was found at https://mathematica.stackexchange.com/questions/15935/execute-code-when-file-is-modified/15938 and seems to not work anymore.

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[];

StartScheduledTask[Kale`task];
StopScheduledTask[Kale`task];
POSTED BY: Luke Jennings
2 Replies
Posted 4 years ago

First, the problem is not with CreateScheduledTask; this is deprecated but still works as of 12.2. Of course, it is good advice to move away from a deprecated function.

But there are a couple things to fix here:

  • In your example as written, you stopped the task immediately after starting it, so as written of course nothing works because the task isn't running; but that may be obvious.
  • The big one: in updatedQ, you're comparing dates using ==, which has 2 equal signs and is called Equal, when you should use ===, 3 equals signs, which is SameQ. When comparing numbers, go with Equal, but for all other programming, SameQ is probably what you want, and that's the case here. The Equal of two dates is returning unevaluated. (I give the names of the operators, since once you know a symbol name, you can look it up in the reference page.)

That should be enough to get it working, but here are some more notes:

  • if the file doesn't exist, FileDate issues a message, which is showing up in the messages window once a second; you can fix this by wrapping Quiet around that. Some people might want to ask FileExistsQ first, but I figure let the FileDate do both jobs of checking existence and date in one stat call.
  • lastModified being initialized to {} looks odd since it's not a date and suggests you expect it to be a list at some point; you could use the symbol None, or even a date in the far past (e.g. beginning of Unix epoch). I would go with None myself.

Hope this helps!

POSTED BY: Joel Klein
Posted 4 years ago

Hi Luke,

Probably because CreateScheduledTask is deprecated (unless you are on V11.2/3). You will have to re-write that code to use SessionSubmit.

POSTED BY: Rohit Namjoshi