在请求期间设置 Time.zone:线程安全? [英] Setting Time.zone during a request: Thread Safe?

查看:42
本文介绍了在请求期间设置 Time.zone:线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的应用程序的用户指定一个时区,然后在每个请求的开头设置他们的时区.在 Rails 中,AFAICT,这是通过设置单例对象来完成的:

I'd like to let users of my app specify a time zone, and then set their time zone at the beginning of each request. In Rails, AFAICT, this is done by setting the singleton object:

Time.zone = "America/Los_Angeles"

我对最佳实践的理解是,一般来说,单例应该设置一次.例如在应用程序配置中.

My understanding of best practices is that, generally speaking, a singleton should be set ONCE. For example in the application configuration.

从对类似问题的回答中,有人建议在 ApplicationController 中进行设置

From an answer to a similar question, someone suggests setting it in the ApplicationController

class ApplicationController < ActionController::Base
  before_filter :set_timezone
  def set_timezone
    # current_user.time_zone #=> 'London'
    Time.zone = current_user.time_zone if current_user && current_user.time_zone
  end
end

这样安全吗?或者我是否有一个线程影响另一个线程的风险?我将尝试运行此测试,但这不是最简单的测试场景,所以我想我应该看看是否有人已经这样做了.

Is this safe? Or do I run a risk of having one thread affect another? I will try running a test of this but it's not the easiest test scenario ever so I thought I should see if someone has already done this.

推荐答案

如果你看一下 代码 在这里实现你可以看到当前区域存储在一个线程局部变量中,所以每个线程都可以设置 Time.zone 而不会干扰其他线程.

If you look at the code where this is implemented you can see that the current zone is stored in a thread local variable, so each thread can set Time.zone without interfering with other threads.

这篇关于在请求期间设置 Time.zone:线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆