I have to run automated work every 5 hours.
I found this post on how to create scheduled tasks using IScheduledTaskHandler and IScheduledTaskManager. Scheduled Tasks Using Orchard CMS
I copied the same code, I added my service call inside the Process function. It compiles fine. But I'm not sure that I need to "start" this scheduled task, for example, start the Windows service. Does this work out automatically after I build the solution? When does the clock start ticking if I want to run this task in 5 hours? And if I want to stop / pause, how can I do this?
Thanks.
EDIT:
I get an exception if I try to enable a custom module with a task handler.
Exception Details: System.ArgumentNullException: The value cannot be null. Parameter Name: Source
Line 241: var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name);
Source file: \ orchard-1.4 \ src \ Orchard \ Environment \ DefaultOrchardHost.cs Line: 241
_shellContexts appears as null. If I remove the task handler class from the project / module, everything will be fine.
Here is the code for the task handler.
public class ScheduledTaskHandler : IScheduledTaskHandler { private const string TaskType = "MyTaskUniqueID"; private readonly IScheduledTaskManager _taskManager; private readonly IMyService _myService; public ILogger Logger { get; set; } public ScheduledTaskHandler(IScheduledTaskManager taskManager, IMyService myService) { _myService = myService; _taskManager = taskManager; Logger = NullLogger.Instance; try { DateTime firstDate = new DateTime().AddMinutes(5); ScheduleNextTask(firstDate); } catch (Exception e) { this.Logger.Error(e, e.Message); } } public void Process(ScheduledTaskContext context) { if (context.Task.TaskType == TaskType) { try { _myService.RunJob(); } catch (Exception e) { this.Logger.Error(e, e.Message); } finally { DateTime nextTaskDate = new DateTime().AddHours(5); 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); } } }
source share