]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/commitdiff
forecast plugin: thread, don't block
authorGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Wed, 29 Aug 2007 20:55:33 +0000 (20:55 +0000)
committerGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Wed, 29 Aug 2007 20:55:33 +0000 (20:55 +0000)
data/rbot/plugins/forecast.rb

index d0847b59c9eb879d9b67b7f99a5370e5baa8ddb4..8079072853084b5ed2d43747f6fad788dd8646dd 100644 (file)
@@ -7,7 +7,8 @@
 # Copyright:: (C) 2006 Ralph M. Churchill
 
 require 'soap/wsdlDriver'
-require 'open-uri'
+# TODO why not use HttpUtil instead of open-uri?
+require 'open-uri' 
 require 'rexml/document'
 require 'erb'
 
@@ -87,6 +88,7 @@ class ForecastPlugin < Plugin
             end
         end
         @forecast_cache = Hash.new
+        @cache_mutex = Mutex.new
     end
 
     def forecast(m,params)
@@ -105,31 +107,40 @@ class ForecastPlugin < Plugin
     end
     
     def get_forecast(m,loc)
+      Thread.new {
         begin
+          @cache_mutex.synchronize do
             if @forecast_cache.has_key?(loc) and
                 Time.new - @forecast_cache[loc][:date] < 3600
                 forecast = @forecast_cache[loc][:forecast]
-                forecast_date = @forecast_cache[loc][:date]
-            else
-                begin
-                    l = LatLong.new
-                    f = Forecast.new(*l.get_lat_long(loc))
-                    forecast,forecast_date = f.forecast
-                rescue => err
-                    m.reply err
+                if forecast
+                  m.reply forecast
+                  Thread.exit
                 end
             end
-            if forecast
-                m.reply forecast
-                @forecast_cache[loc] = {}
-                @forecast_cache[loc][:forecast] = forecast
-                @forecast_cache[loc][:date] = forecast_date
-            else
-                m.reply "Couldn't find forecast for #{loc}"
+          end
+          begin
+            l = LatLong.new
+            f = Forecast.new(*l.get_lat_long(loc))
+            forecast,forecast_date = f.forecast
+          rescue => err
+            m.reply err
+          end
+          if forecast
+            m.reply forecast
+            @cache_mutex.synchronize do
+              @forecast_cache[loc] = {
+                :forecast => forecast,
+                :date => forecast_date
+              }
             end
+          else
+            m.reply "Couldn't find forecast for #{loc}"
+          end
         rescue => e
-            m.reply "ERROR: #{e}"
+          m.reply "ERROR: #{e}"
         end
+      }
     end
 end
 plugin = ForecastPlugin.new