kevherro
kevherro

Reputation: 1

Time-based conditional query

Suppose I have the following Server data model:

Server
-> created_at Timestamp
-> last_ping Timestamp

A "stale" Server is defined as a Server whose last_ping occurred more than one hour ago (i.e., last_ping < Time.now - 1 hour). It should be destroyed if there exists another non-stale server that has come online (created_at) within one hour of the last_ping of the stale server.

How can I find all the Servers that should be destroyed? What would a query look like for this?

Upvotes: 0

Views: 46

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66244

Something like…

def clean_stale_servers
  return unless Server.exists?(last_ping: 1.hour..)

  Server.where(last_ping: ...1.hour.ago)
    .destroy_all # .delete_all is faster, use that if possible
end

Then you can call the clean_stale_servers method periodically, i.e. from a cronjob.

Upvotes: 1

Related Questions