Recipe 3.12. Running a Code Block PeriodicallyProblemYou want to run some Ruby code (such as a call to a shell command) repeatedly at a certain interval. SolutionCreate a method that runs a code block, then sleeps until it's time to run the block again:
DiscussionThere are two main times when you'd want to run some code periodically. The first is when you actually want something to happen at a particular interval: say you're appending your status to a log file every 10 seconds. The other is when you would prefer for something to happen continuously, but putting it in a tight loop would be bad for system performance. In this case, you compromise by putting some slack time in the loop so that your code isn't always The implementation of every_n_seconds deducts from the sleep time the time spent running the code block. This ensures that calls to the code block are spaced evenly apart, as close to the desired interval as possible. If you tell every_n_seconds to call a code block every five seconds, but the code block takes four seconds to run, every_n_seconds only sleeps for one second. If the code block takes six seconds to run, every_n_seconds won't sleep at all: it'll come back from a call to the code block, and immediately yield to the block again. If you always want to sleep for a certain interval, no matter how long the code block takes to run, you can simplify the code:
In most cases, you don't want every_n_seconds to take over the main loop of your program. Here's a version of every_n_seconds that spawns a separate thread to run your task. If your code block stops the loop by with the break keyword, the thread stops running:
In this snippet, I use every_n_seconds to spy on a file, waiting for
That example might give output like this, if someone on the system is working on the file /tmp/foo:
See Also
|
Saturday, October 31, 2009
Recipe 3.12. Running a Code Block Periodically
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment