2017-09-26 93 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