1

我想在我的控制器中使用一个计时器来完成一项特定的工作。

下面是代码

    public class ProductsController : ApiController
    {

        private readonly System.Timers.Timer _checkTimer = new System.Timers.Timer();
        public readonly int CheckTimerInterval = 10 * 30 * 1000;

        public ProductsController()
        {
            _checkTimer.Elapsed += CheckTimerElapsed;
            _checkTimer.Interval = this.CheckTimerInterval;
            _checkTimer.Enabled = true;
        }

        private void CheckTimerElapsed(object source, ElapsedEventArgs e)
        { 
          //Do the processing
        }
     }

但问题是每当我调用控制器时,都会创建一个新的 Timer 实例。

我只想要一个计时器实例。你能帮我实现这个吗?

我知道在控制器中使用 Timer 不是一个好主意,但我没有其他选择。我使用此控制器将请求分配给临时用户。在 Timer 中,我需要获取所有作业并将其分配给实际用户。

4

2 回答 2

2

You can use your same code in a static class under one method. Then call that method under Global.asax.cs file under your Application_Start() method

public static class GlobalValues
{
    private static System.Timers.Timer bomreporttimer;
    public static void StartScrapBom()
    {
        bomreporttimer = new System.Timers.Timer();
        bomreporttimer.Elapsed += Bomreporttimer_Elapsed;
        bomreporttimer.Interval = 1000 * 60 * 15;
        bomreporttimer.Enabled = true;
    }
}

Global.asax.cs file

 public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        GlobalValues.GlobalValues.StartScrapBom();
    }
}
于 2019-04-10T07:45:21.140 回答
0

首先,您不应该这样做,尝试找到您要解决的问题并尝试其他解决方案。

但无论如何,您需要有一个静态的计时器实例,所以您可以简单地将其设为静态,您也可以使用 IOC 来做到这一点。将它放在类似代码的地方可能会更好startupglobal_asax以表明它是全局的和静态的。顺便说一句,您还需要考虑线程,因此可以将其设为单曲。

再一次,不要这样做。

于 2018-12-05T14:42:09.543 回答