Last active
December 23, 2015 21:39
-
-
Save robertiagar/6697705 to your computer and use it in GitHub Desktop.
A wrapper class used to schedule a task in the asp.net thread pool. Currently a prototype.
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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ScheduledTasks | |
{ | |
public class TaskWrapper | |
{ | |
public TaskWrapper(TimeSpan period, Action taskToRun, int taskId, string appDataFolderPath) | |
{ | |
this.Period = period; | |
this.TaskId = taskId; | |
this._taskToRun = taskToRun; | |
this._appDataFolder = appDataFolderPath; | |
this._lastTimeRan = DateTime.Now; | |
} | |
public bool ShouldIRun | |
{ | |
get | |
{ | |
return DateTime.Now - _lastTimeRan > Period; | |
} | |
} | |
public void Start() | |
{ | |
var t = new Task(() => | |
{ | |
while (true) | |
{ | |
if (ShouldIRun) | |
{ | |
Task.Factory.StartNew(_taskToRun); | |
_lastTimeRan = DateTime.Now; | |
} | |
} | |
}); | |
t.Start(); | |
} | |
public TimeSpan Period { get; private set; } | |
private Action _taskToRun; | |
private string _appDataFolder; | |
private DateTime _lastTimeRan | |
{ | |
get | |
{ | |
using (var stream = new StreamReader(_appDataFolder + "/tasks/" + TaskId)) | |
{ | |
var date = DateTime.Parse(stream.ReadToEnd()); | |
return date; | |
} | |
} | |
set | |
{ | |
if (!File.Exists(_appDataFolder + "/tasks/" + TaskId)) | |
{ | |
Directory.CreateDirectory(_appDataFolder + "/tasks/"); | |
File.Create(_appDataFolder + "/tasks/" + TaskId).Close(); | |
} | |
using (var stream = new StreamWriter(_appDataFolder + "/tasks/" + TaskId)) | |
{ | |
stream.Write(value); | |
} | |
} | |
} | |
public int TaskId { get; private set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment