Skip to content

Instantly share code, notes, and snippets.

@sriki77
Created December 26, 2011 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sriki77/1520952 to your computer and use it in GitHub Desktop.
Save sriki77/1520952 to your computer and use it in GitHub Desktop.
Timer & Deferred Eval & GC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace TimerDeferredEval
{
class JobScheduler : IDisposable
{
private static readonly TimeSpan DueTime = new TimeSpan(0, 0, 0, 5);
private static readonly TimeSpan Period = new TimeSpan(0, 24, 0);
private readonly IEnumerable<TimerCallback> _jobs;
private IEnumerable<Timer> _timers;
public JobScheduler(IEnumerable<TimerCallback> jobs)
{
_jobs = jobs;
}
public void Start()
{
_timers = _jobs.Select(job =>
{
Console.Error.WriteLine("Timer Created...");
return new Timer(job, null, DueTime, Period);
}); // Deferred Execution
_timers.Count(); // Eager Evaluation
Console.Error.WriteLine(_timers.GetType());
}
public void Dispose()
{
foreach (var timer in _timers)
{
timer.Dispose();
}
}
}
class Program
{
static void Main(string[] args)
{
JobScheduler scheduler = new JobScheduler(new List<TimerCallback>{DoWorkOnTimer});
scheduler.Start();
GC.Collect();
Thread.Sleep(10000);
scheduler.Dispose();
}
static void DoWorkOnTimer(Object data)
{
Console.Error.WriteLine("Timer Fired...");
}
}
}
class JobScheduler : IDisposable
{
private static readonly TimeSpan DueTime = new TimeSpan(0, 10, 0);
private static readonly TimeSpan Period = new TimeSpan(0, 24, 0);
private readonly IEnumerable<TimerCallback> _jobs;
private IEnumerable<Timer> _timers;
public JobScheduler(IEnumerable<TimerCallback> jobs) { _jobs = jobs;}
public void Start() {
_timers = _jobs.Select(job => new Timer(job, null, DueTime, Period) }); // Loc 1.
_timers.Count(); // Loc 2. }
public void Dispose() {
foreach (var timer in _timers) timer.Dispose(); // Loc 3.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment