Scheduled tasks using Orchard CMS

2019-01-25 21:43发布

I need to create scheduled task using Orchard CMS.

I have a service method (let's say it loads some data from external source), and I need to execute it everyday at 8:00 AM.

I figured out I have to use IScheduledTaskHandler and IScheduledTaskManager... Does anyone know how to solve this problem? Some sample code will be appriciated.

1条回答
Viruses.
2楼-- · 2019-01-25 22:09

In your IScheduledTaskHandler, you have to implement Process to provide your task implementation (I Advise you to put your implementation in another service class), and you have to register your task in the task manager. Once in the Handler constructor to register the first task, and then in the process implementation, to ensure that once a task was executed, the next one is scheduled.

Here is a sample:

public class MyTaskHandler : IScheduledTaskHandler
{
  private const string TaskType = "MyTaskUniqueID";
  private readonly IScheduledTaskManager _taskManager;

  public ILogger Logger { get; set; }

  public MyTaskHandler(IScheduledTaskManager taskManager)
  {
    _taskManager = taskManager;
    Logger = NullLogger.Instance;
    try
    {
      DateTime firstDate = //Set your first task date (utc).
      ScheduleNextTask(firstDate);
    }
    catch(Exception e)
    {
       this.Logger.Error(e,e.Message);
    }
  }

  public void Process(ScheduledTaskContext context)
  {
     if (context.Task.TaskType == TaskType)
     {
       try
       {
               //Do work (calling an IService for instance)
       }
       catch (Exception e)
       {
         this.Logger.Error(e, e.Message);
       }
       finally
       {
         DateTime nextTaskDate = //Your next date (utc).
         this.ScheduleNextTask(nextTaskDate);
       }         
     }
  }
  private void ScheduleNextTask(DateTime date)
  {
     if (date > DateTime.UtcNow )
     {
        var tasks = this._taskManager.GetTasks(TaskType);
        if (tasks == null || tasks.Count() == 0)
          this._taskManager.CreateTask(TaskType, date, null);
      }
  }


}
查看更多
登录 后发表回答