2017-09-26 66 views
0

在我的webapi应用程序中,我想在特定时间安排行动。这里是我的代码:webapi:在特定时间安排行动

 private readonly ConcurrentDictionary<string, Timer> timers; 

     public void Schedule(TimeSpan when, Action<ElapsedEventArgs, Item> expiredCallback, Item item) 
     { 
      Timer timer = null; 

      if (timers.TryGetValue(item.Label, out timer)) 
      { 
       return; 
      } 

      timer = new Timer(); 
      timer.Interval = when.TotalMilliseconds; 
      var addResult = this.timers.TryAdd(item.Label, timer); 
      if (addResult) 
      { 
       timer.Elapsed += (sender, e) => 
       { 
        Timer expiredTimer = null; 

        if (this.timers.TryRemove(item.Label, out expiredTimer)) 
        { 
         expiredTimer.Enabled = false; 
         expiredTimer.Dispose(); 
        } 

        expiredCallback(e, item); 
       }; 

       timer.Start(); 
      } 

     } 

这段代码的问题是,如果应用程序池回收后,我安排一个动作,我假设的动作将不会被执行,因为计时器保持在内存中。

更好的解决方案是使用调度程序API调度任务并从该调度任务调用API,但这会使事情变得复杂......因此,是否有一种简单方法可以使此代码在场景中工作已经描述过?

+1

我认为[quartz.net(https://www.quartz-scheduler.net/)应该是足够好这个场景。为什么不使用它? –

+1

您可以使用Hangfire,您可以将服务器存储设置为数据库。所以,所有的调度元数据都将存储在数据库中,应用程序池回收不会影响它 –

+0

推测为此使用真正的调度框架的建议。 – NWard

回答

0

Postgres,有控制shedules的pgAgent。这是一个免费的easy_to_use time sheduler,您可以在那里收集所有需要运行的任务。所有任务都保存在表中,因此如果Web服务器重新启动,则不会丢失任何内容。如果一个shedule失败,它会登录tablelog。

pgagent的示例选项(我的本地服务器)。

enter image description here

enter image description here

相关问题