Created
July 12, 2018 16:28
-
-
Save rhullah/d2874e420dfa8130cbd92596c57bbd78 to your computer and use it in GitHub Desktop.
This is an example of a sample task that reschedules itself, thus creating a recurring task. This is initially kicked off in the Global.asax/Bootstrap section calling MyScheduledTask.ScheduleTask(true).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyScheduledTask : ScheduledTask | |
{ | |
public static readonly string MyKey = "<hard coded guid string>"; | |
public MyScheduledTask() | |
{ | |
Key = MyKey; | |
} | |
public override void ExecuteTask() | |
{ | |
try | |
{ | |
// Do the actual task work | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex, ConfigurationPolicy.ErrorLog); | |
} | |
finally | |
{ | |
ScheduleTask(); | |
} | |
} | |
// The runNow argument should really only be used for local testing/debugging | |
public static void ScheduleTask(bool clearExisting = false, bool runNow = false) | |
{ | |
try | |
{ | |
SchedulingManager manager = new SchedulingManager(); | |
if (clearExisting) | |
{ | |
var taskName = typeof(MyScheduledTask).FullName; | |
var allTasks = manager.GetTaskData().Where(x => x.TaskName == taskName).ToList(); | |
if (allTasks.Any()) | |
{ | |
foreach (var task in allTasks) | |
{ | |
task.IsRunning = false; | |
manager.DeleteTaskData(task); | |
} | |
manager.SaveChanges(); | |
Log.Write("Deleted old tasks for MyScheduledTask", ConfigurationPolicy.Trace); | |
} | |
} | |
Log.Write("Creating New MyScheduledTask", ConfigurationPolicy.Trace); | |
CreateTask(manager, runNow); | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex, ConfigurationPolicy.ErrorLog); | |
} | |
} | |
private static void CreateTask(SchedulingManager manager, bool runNow = false) | |
{ | |
// GetExecuteTime() is up to your implementation, but make sure result is in UTC | |
DateTime executeTime = runNow ? DateTime.UtcNow.AddSeconds(10) : GetExecuteTime(); | |
Log.Write($"Creating a new task to run next at UTC {executeTime}", ConfigurationPolicy.Trace); | |
MyScheduledTask newTask = new MyScheduledTask() | |
{ | |
ExecuteTime = executeTime, | |
Description = $"My Scheduled Task, scheduled to run at: UTC {executeTime.ToString("o")}" | |
}; | |
manager.AddTask(newTask); | |
manager.SaveChanges(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment