2017-04-02 22 views
0

.NET Framework 4.5.2 Web APIでFluentSchedulerを使用できません。数日前、私はコンソールアプリケーションを介してスケジューリングについて同様の質問をし、助けを借りて残念ながら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

Localhostで実行できますか? – coder771

関連する問題