Scheduled tasks using Orchard CMS

可紊 提交于 2019-11-28 01:59:31

问题


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:


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


}


来源:https://stackoverflow.com/questions/8916146/scheduled-tasks-using-orchard-cms

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