ruby - Rails with mutex on class variable, rake task and cron -
sorry such big question. not have experience rails threads , mutex.
i have class follow used different controllers license each customers.
customers , licenses gets added , removed every hour. api available customers , licenses.
i plan create rake task call update_set_customers_licenses, run hourly via cronjob.
i have following questions:
1) mutex, there potential problem, there chance rake task can occur while updating. idea on how solve this?
2) design below writes json out file, done safety api not reliable. can seen, not reading file back, in essence file write useless. tried implement file read mutex , rake task, gets confusing. pointers here.
class customer @@customers_to_licenses_hash = nil @@last_updated_at = nil @@mutex = mutex.new customers_licenses_file = "#{rails.root}/tmp/customers_licenses" def self.cached_license_with_customer(customer) rails.cache.fetch('customer') {self.license_with_customer(customer)} end def self.license_with_customer(customer) @@mutex.synchronize license = @@customers_to_licenses_hash[customer] if license return license elsif(@@customers_to_licenses_hash.nil? || time.now.utc - @@last_updated_at > 1.hours) updated = self.update_set_customers_licenses return @@customers_to_licenses_hash[customer] if updated else return nil end end end def self.update_set_customers_licenses updated = nil file_write = file.open(customers_licenses_file, 'w') results = self.get_active_customers_licenses if results @@customers_to_licenses_hash = results file_write.print(results.to_json) @@last_updated_at = time.now.utc updated = true end file_write.close updated end def self.get_active_customers_licenses #http thru api #return hash of records end end
i'm pretty it's case every time rails loads, environment "fresh" , has no concept of "state" in between instances. say, mutex in 1 ruby instance (the 1 request rails) has no effect on second ruby instance (another request rails or in case, rake task).
if follow data upstream, you'll find common root of every instance can used synchronize them database. use transactional blocks or maybe manual flag set , unset in database.
Comments
Post a Comment