Scheduled tasks using Orchard CMS

…衆ロ難τιáo~ 提交于 2019-11-29 08:17:50

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


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!