0

我无法让 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);
    }
4

1 回答 1

3

终于解决了这个问题。原来问题出在我的注册表类上。我不得不改变它如下。

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 会变得很棘手,因为我们必须处理应用程序池回收、空闲时间等。但这看起来是一个好的开始。

于 2017-04-02T21:15:00.317 回答