2017-04-02 68 views
0

我無法讓FluentScheduler在.Net Framework 4.5.2 Web api中工作。幾天前,我問了一個關於通過控制檯應用程序進行調度的類似問題,並且可以讓它與幫助一起工作,但不幸的是現在面臨Web Api的問題。以下是代碼。如何使用Web API使用FluentScheduler庫來安排作業?

[HttpPost] 
    [Route("Schedule")] 
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel) 
    { 
     var registry = new Registry(); 
     registry.Schedule<MyJob>().ToRunNow(); 
     JobManager.Initialize(registry); 
     JobManager.StopAndBlock(); 
     return Json(new { success = true, message = "Scheduled!" }); 
    } 

下面是我要安排這對於現在只是寫文本文件

public class SampleJob: IJob, IRegisteredObject 
{ 
    private readonly object _lock = new object(); 
    private bool _shuttingDown; 

    public SampleJob() 
    { 
     HostingEnvironment.RegisterObject(this); 
    } 

    public void Execute() 
    { 
     lock (_lock) 
     { 
      if (_shuttingDown) 
       return; 
      //Schedule writing to a text file 
      WriteToFile(); 
     } 
    } 

    public void WriteToFile() 
    { 
     string text = "Random text"; 
     File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text); 
    } 

    public void Stop(bool immediate) 
    { 
     lock (_lock) 
     { 
      _shuttingDown = true; 
     }    
     HostingEnvironment.UnregisterObject(this); 
    } 

回答

2

得到這個終於解決了工作。事實證明,問題出在我的註冊表類。我不得不改變它如下。

public class ScheduledJobRegistry: Registry 
{ 
    public ScheduledJobRegistry(DateTime appointment) 
    { 
     //Removed the following line and replaced with next two lines 
     //Schedule<SampleJob>().ToRunOnceIn(5).Seconds(); 
     IJob job = new SampleJob(); 
     JobManager.AddJob(job, s => s.ToRunOnceIn(5).Seconds()); 
    } 

} 

    [HttpPost] 
    [Route("Schedule")] 
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel) 
    { 
     JobManager.Initialize(new ScheduledJobRegistry());      
     JobManager.StopAndBlock(); 
     return Json(new { success = true, message = "Scheduled!" }); 
    } 

還有一點要注意:我能得到這個工作,但在IIS託管API很棘手,因爲我們要處理的應用程序池回收,閒置時間等。但是,這看起來像一個良好的開端。

+0

它可以在本地主機上運行嗎? – coder771