Is sleep() a good idea for the main loop of a job-scheduling app

Yoann Le Touche picture Yoann Le Touche · Jul 24, 2009 · Viewed 8.3k times · Source

I'm writing a job-scheduling app in Ruby for my work (primarily to move files using various protocol at a given frequency)

My main loop looks like this :

while true do
  # some code to launch the proper job
  sleep CONFIG["interval"]
end

It's working like a charm, but I'm not really sure if it is safe enough as the application might run on a server with cpu-intensive software running.

Is there another way to do the same thing, or is sleep() safe enough in my case ?

Answer

jrockway picture jrockway · Jul 24, 2009

Any time I feel the need to block, I use an event loop; usually libev. Here is a Ruby binding:

http://rev.rubyforge.org/rdoc/

Basically, sleep is perfectly fine if you want your process to go to sleep without having anything else going on in the background. If you ever want to do other things, though, like sleep and also wait for TCP connections or a filehandle to become readable, then you're going to have to use an event loop. So, why not just use one at the beginning?

The flow of your application will be:

main {
   Timer->new( after => 0, every => 60 seconds, run => { <do your work> } )
   loop();
}

When you want to do other stuff, you just create the watcher, and it happens for you. (The jobs that you are running can also create watchers.)