Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

TimerTask as Filewatcher.

Thread view: 
smartnhandsome - 31 Oct 2007 23:02 GMT
Hi All,
I want to use TimerTask to watch for a file in a particular folder.
and proceed to another line of code only after i get the file in a
particular folder. The TimerTask does it well but a seperate thread i
guess I want to

new FileWatcher("c://temp3//",file,1000);
do this line1;
do this line2;

I want to do this line1 and do this line2 only after i get the file
i.e. I want to return from watchFile method only after get the file.
This code now starts to watch for a file as a seperate thread so the
do this line1 do this line2 also Execute while the filewatcher class
is still looking for the class.

Any Suggestions. Any Help Is appreciated.

public class FileWatcher {

    Timer timer;

    private String fileToWatch;

    private String directorytoWatch;

    private int timeDelay;

    public FileWatcher(String directorytoWatch, String file, int
timeInterval) {
        this.fileToWatch = file;
        this.directorytoWatch = directorytoWatch;
        this.timeDelay = timeInterval;
        timer = new Timer();
        TimerTask timerTask =new FileWatcherTask();

        timer.schedule(timerTask, 0, // initial delay
                1 * timeDelay); // subsequent rate

    }

    class FileWatcherTask extends TimerTask {

        public void run() {
            File theDirectory = new File(directorytoWatch);
            File[] children = theDirectory.listFiles();

            // Store all the current files and their timestamps
            for (int i = 0; i < children.length; i++) {

                File file = children[i];
                if (file.getName().equals(fileToWatch)) {
                    System.out.println("File Found");
                    System.exit(0);
                } else {
                    System.out.println("File " + fileToWatch+ "  not found yet");
                }

            }
            theDirectory = null;
            children = null;
            System.gc();
        }
    }

}
Knute Johnson - 31 Oct 2007 23:39 GMT
> Hi All,
> I want to use TimerTask to watch for a file in a particular folder.
[quoted text clipped - 62 lines]
>
> }

import java.io.*;
import java.util.*;

public class test {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                File f = new File("c://temp3//");
                if (f.exists()) {
                    cancel();  // so it doesn't do it again
                    // do your thing here
                }
            }
        };
        timer.schedule(task,1000,1000);  // try every second
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Lew - 01 Nov 2007 00:02 GMT
smartnhandsome wrote:
>> I want to use TimerTask to watch for a file in a particular folder.
>> and proceed to another line of code only after i get the file in a
>> particular folder.

> import java.io.*;
> import java.util.*;
[quoted text clipped - 14 lines]
>     }
> }

Now, finding out if that file not only exists but is complete, that's another
issue.  You could find the file and another process might still be writing to
it.

Signature

Lew

Knute Johnson - 01 Nov 2007 00:56 GMT
> smartnhandsome wrote:
>>> I want to use TimerTask to watch for a file in a particular folder.
[quoted text clipped - 23 lines]
> another issue.  You could find the file and another process might still
> be writing to it.

See the "//do your thing" comment above :-).

Signature

Knute Johnson
email s/nospam/knute/

Martin Gregorie - 01 Nov 2007 01:49 GMT
> Now, finding out if that file not only exists but is complete, that's
> another issue.  You could find the file and another process might still
> be writing to it.

Shouldn't be a problem provided that the writer completes the file,
closes it and then renames it to something that the reader is expecting.

We used that approach in a production system where files were delivered
by FTP and renamed when the PUT operation completed. It worked fine: we
had no problems with incomplete files.

Signature

martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |

smartnhandsome - 01 Nov 2007 04:51 GMT
Thanks every one for there replies, but the code still works like the
same way as I had written, when we create a TimerTask and override the
run method and pass this to timer it creates a new thread and then
pass back the control to the main thread, so the main thread still
keeps doing next steps while the timer thread that was created earlier
would run back ground. I wanted my code (main thread ) to wait till
timer task thread finishes its file watch. How can this be achieved??

Thanks again for every ones posts.
Knute Johnson - 01 Nov 2007 05:47 GMT
> Thanks every one for there replies, but the code still works like the
> same way as I had written, when we create a TimerTask and override the
[quoted text clipped - 5 lines]
>
> Thanks again for every ones posts.

do {
    File f = new File("????");
    if (f.exists())
        break;
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ie) { }
} while (true) ;

But if the file never shows up your program never runs again.  I would
use this instead of a TimerTask, it is inline and simpler if you want to
halt your program until the file arrives.

If you insist on a TimerTask;

use a boolean flag and a wait object

boolean flag;
final Object o = new Object();

// main thread
synchronized (o) {
    while (!flag)
        o.wait();
    flag = false;
}

// TimerTask...
if (f.exists())
    synchronized (o) {
        flag = true;
        o.notify();
    }

Signature

Knute Johnson
email s/nospam/knute/

smartnhandsome - 02 Nov 2007 04:40 GMT
Knute
Thanks for your post i tried using your suggestion on synchronized
block with TimerTask but i was getting Illegal State Exception. I did
not understand why you were passing Object o into the block?.But your
simple inline sleep code was working fine. Thanks again.
Knute Johnson - 02 Nov 2007 04:59 GMT
> Knute
>  Thanks for your post i tried using your suggestion on synchronized
> block with TimerTask but i was getting Illegal State Exception. I did
> not understand why you were passing Object o into the block?.But your
> simple inline sleep code was working fine. Thanks again.

I'm a firm believer in the KISS method.

The Object o is just so that you can get a lock from a common object.
The lock is used to synchronize the actions.  Thread interactions are
very complex and a science into themselves.

Signature

Knute Johnson
email s/nospam/knute/

Lew - 02 Nov 2007 05:14 GMT
smartnhandsome wrote:
>>  Thanks for your post i [sic] tried using your suggestion on synchronized
>> block with TimerTask but i [sic] was getting Illegal State Exception.

Did you mean IllegalStateException?

Signature

Lew

Daniel Pitts - 02 Nov 2007 02:09 GMT
> smartnhandsome wrote:
>>> I want to use TimerTask to watch for a file in a particular folder.
[quoted text clipped - 23 lines]
> another issue.  You could find the file and another process might still
> be writing to it.

Generally, most OSes have a way to rename a file as an atomic operation.
 Doing this allows you to create the file under a different name, fill
it appropriately, and then rename it to what its supposed to.  Barring
that, you should obtain a lock on the file (not sure Java supports that).

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Roedy Green - 01 Nov 2007 01:50 GMT
On Wed, 31 Oct 2007 15:02:05 -0700, smartnhandsome
<smartnhandsome@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>I want to do this line1 and do this line2 only after i get the file
>i.e. I want to return from watchFile method only after get the file.
>This code now starts to watch for a file as a seperate thread so the
>do this line1 do this line2 also Execute while the filewatcher class
>is still looking for the class.

You would have to sleep until you found what you wanted.
see http://mindprod.com/jgloss/sleep.html

A more Javaesque solution would be to pass a delegate object to your
watcher.  The watcher calls a method in the delegate object every time
it finds the requested file.
http://mindprod.com/jgloss/callback.html
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.