简体   繁体   English

如何使用FluentScheduler库和Web Api安排工作?

[英]How to schedule a job using FluentScheduler library with Web Api?

I am unable to get FluentScheduler working in .Net Framework 4.5.2 Web api. 我无法在.Net Framework 4.5.2 Web api中使用FluentScheduler。 Few days ago, I asked a similar question about scheduling through Console application and could get it to work with help but unfortunately facing issues with Web Api now. 几天前,我问了一个类似的问题,关于如何通过控制台应用程序进行调度,是否可以在帮助下使用它,但是现在不幸的是Web Api面临问题。 Below is the code. 下面是代码。

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

Below is the job I want to schedule which for now is just writing text to a file 以下是我要安排的工作,目前仅将文本写入文件

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

Got this resolved finally. 终于解决了。 It turns out the issue was with my Registry class. 原来问题出在我的注册表类上。 I had to change it as follows. 我不得不按如下方式进行更改。

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!" });
    }

Another point to note: I could get this to work but hosting Api in IIS makes it tricky because we have to deal with App Pool recycles, idle time etc. But this looks like a good start. 还有一点需要注意:我可以使它正常工作,但是在IIS中托管Api会很棘手,因为我们必须处理App Pool的回收,空闲时间等。但这看起来是一个不错的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM