Skip to content

Instantly share code, notes, and snippets.

@ruslander
Created April 12, 2011 21:38
Show Gist options
  • Save ruslander/916478 to your computer and use it in GitHub Desktop.
Save ruslander/916478 to your computer and use it in GitHub Desktop.
A task scheduler which will escape current tick if is busy with previous
public class TaskScheduler
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Timer _timer;
public ServiceContext(DrawingsController controller, IAppConfig config): base(controller)
{
var _interval = 1000 * 60 * config.DrawEveryNMinutes;
_timer = new Timer(_interval) { AutoReset = true };
Log.DebugFormat("Drawing will be executed every {0} min", _interval);
}
// This is the synchronization point that prevents events
// from running concurrently, and prevents the main thread
// from executing code after the Stop method until any
// event handlers are done executing.
private static int syncPoint = 0;
public override void OnInit()
{
_timer.Start();
_timer.Elapsed += (sender, e) =>
{
Log.DebugFormat("Executing as time elapsed at: {0}", DateTime.Now);
if (Interlocked.CompareExchange(ref syncPoint, 1, 0) == 0){
Execute();
syncPoint = 0;
}
else
Log.DebugFormat("Previous Drawing is still going on, this one will be skipped");
};
}
public override void Dispose()
{
_timer.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment