开发者

Monitor a file for changes

开发者 https://www.devze.com 2023-03-17 22:08 出处:网络
I have been searching the web for good ideas on creating an application. service, or vb script that will constantly monitor a file for changes.However, I want it to alert me when there are NO changes.

I have been searching the web for good ideas on creating an application. service, or vb script that will constantly monitor a file for changes. However, I want it to alert me when there are NO changes. The file I am monitoring is a log created by a very important application. If that fi开发者_如何学编程le stops growing then that means there is something wrong with the application and it has stopped writing to the log file.

Does anyone have any ideas? I have played around with the FileSystemWatcher class in C# but I don't know if there is a way to use to alert when a file does not change since all of the events look at changes.

Thank you.


Just use a timer that fires on an interval that that file should be updated in.

Check the file size (FileInfo.Length) and if it is the same as the last time the timer fired, it is not growing.


In this case you don't need a watcher, you could use a timer. Every few minutes (or whatever fits your needs), check the file size. Store the last size somewhere. The next time you check it, compare the previous value to the current one. If they are the same then the file has not changed and you can issue your alert.


A file doesn't change most of the time. You need to define a time period beyond which the logging process is considered to have stopped. Start a timer that (when it completes) will signal that logging has stopped. Reset the timer every time a change event rolls in.


You can use the FileSytemWatcher class:
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

update: well, it pays to read the question through to the end... You can set a Timer (ref) for the duration of inactivity you want to be alerted of and reset the timer in FileSystemWatcher events.


I suggest you to combine all answers you already got.

Use FileSytemWatcher class to watch for changes and use a timer to wait for some period of time since last change.

The simplest solution will look like ManualResetEvent and DateTime variables (don't forget memory barriers) and a background thread.

So, you'll have a something like this:

DateTime _lastChangeTime;
ManualResetEvent _exitEvent; // set this event to exit thread.

private void Watcher_Change(...)
{
    _lastChangeTime = DateTime.UtcNow;
    Thread.MemoryBarrier();
}


private void ThreadProc()
{
    while (_exitEvent.Wait(1000)) // every second
    {
        Thread.MemoryBarrier();

        if (DateTime.UtcNow.Subtract(lastChangeTime) > [some reasonable time])
        {
            // shit happens...
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消