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?
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