0

I'm developing an app. The operating system I'm using is linux. I need to run if possible a ruby script on the file created in the directory. I need to keep this script always running. The first thing I thought about is inotify:

The inotify API provides a mechanism for monitoring file system events. Inotify can be used to monitor individual files, or to monitor directories.

It's exactly what I need, then I found "rb-inotify", a wrapper fir inotify.

Do you think there is a better way of doing what I need than using inotify? Also, I really don't understand the way that I have to use rb-inotify.

I just create, for example, a rb file with:

notifier = INotify::Notifier.new
notifier.watch("directory/to/check",:create) do |event|
    #do task with event.name file
end

notifier.run

Then I just ruby myRBNotifier.rb, and it will stay looping for ever. How do I stop it? Any idea? Is this a good approach?

sawa
  • 165,429
  • 45
  • 277
  • 381
Andres
  • 11,439
  • 12
  • 48
  • 87

3 Answers3

2

I'd recommend looking at god. It's designed for this sort of task, and makes it pretty easy to build a monitoring system for background and daemon apps.

As for the main code itself, inotify isn't cross-platform, so if you have a possibility you'll need to run on Windows or Mac OS then you'll need a different solution. It's not too hard to write a little piece of code that checks your target directory periodically for a change. If you need to know what changed, read and cache the directory entries then compare them the next time your code runs. Use sleep between runs to wait some period of time before looping.

The old-school method of doing similar things is to use cron to fire off a job at regular intervals. That job can be your script that checks whether the file list changed by comparing it to the cached version, then acting as needed if something is different.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

Just run your script in the background with

ruby myRBNotifier.rb &

When you need to stop it, find the process id and use kill on it:

ps ux
kill [whatever pid your process gets from the OS]

Does that answer your question?

jboursiquot
  • 1,261
  • 11
  • 8
  • Running it in the background only works while the session is attached. If the user logs out or their session dies the app will be killed. `screen` could be used to allow detaching and reattaching, but that complicates the solution. – the Tin Man Nov 30 '12 at 05:34
0

If you're running on a mac/unix machine, look at the launchctl man page. You can set up a process to run and execute a ruby script whenever a file changes. It's highly configurable.

Alfie Hanssen
  • 16,964
  • 12
  • 68
  • 74