Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's best way to keep a ruby process run forever?

Tags:

ruby

I have to run a file.rb that make a micro-task (Insert a qwuery into a database) every second.

I have used a for loop (1..10^9) but I got a CPU usage exceed alert! So what's the best way to not waste all CPU?

like image 801
sparkle Avatar asked Oct 25 '25 00:10

sparkle


1 Answers

The simplest way to run forever is just to loop

loop do
  run_db_insert
  sleep 1
end

If it's important that you maintain a 1 Hz rate, note that the DB insert takes some amount of time, so the one-second sleep means each cycle takes dbtime+1 second and you will steadily fall behind. If the DB interaction is reliably less than a second, you can modify the sleep to adjust for the next one-second interval.

loop do
  run_db_insert
  sleep(Time.now.to_f.ceil - Time.now.to_f)
end
like image 88
dbenhur Avatar answered Oct 26 '25 19:10

dbenhur