如何使用带Web Api的FluentScheduler库安排作业?

时间:2017-04-02 00:53:43

标签: c# asp.net-web-api fluentscheduler

我无法让FluentScheduler在.Net Framework 4.5.2 Web api中工作。几天前,我问了一个关于通过控制台应用程序进行日程安排的类似问题,可以让它在帮助下工作但不幸的是现在面临Web Api的问题。以下是代码。

    [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);
    }

1 个答案:

答案 0 :(得分:3)

终于解决了这个问题。事实证明问题出在我的Registry类中。我不得不改变如下。

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使它变得棘手,因为我们必须处理App Pool回收,空闲时间等。但这看起来是一个良好的开端。