Search code examples
c#asp.net-web-apifluentscheduler

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

Solution

  • 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.