pontoNETpt
A comunidade PontoNetPT está direccionada a todos os programadores que trabalhem com a plataforma .NET.
Usando a Cache do ASP.NET como um Agendador de Tarefas

Usando a cache do ASP.NET, é muito simples criar um mecanismo simples de agendamento de tarefas, por exemplo, um que levante um evento a cada X minutos. Uma vez escrevi um módulo simple para fazer precisamente isso, aqui vai o seu código. Cabe-vos a voçês melhorá-lo de acordo com as vossas necessidades!

public class SchedulerModule: IHttpModule
	{
		#region Public constructor
		public SchedulerModule()
		{
			this.Enabled = true;			
			this.Interval = TimeSpan.FromMinutes(1);	//dispara a cada minuto
			this.FirstTime = true;
		}
		#endregion

		#region Public properties
		public Boolean Enabled
		{
			get;
			set;
		}

		public TimeSpan Interval
		{
			get;
			set;
		}

		public Boolean FirstTime
		{
			get;
			private set;
		}
		#endregion

		#region Public events
		public event EventHandler Tick;
		public event EventHandler Start;
		public event EventHandler Stop;
		#endregion

		#region Protected methods
		protected void StartScheduler()
		{
			CacheItemRemovedCallback callback = null;
			HttpContext context = HttpContext.Current;

			callback = delegate(String key, Object value, CacheItemRemovedReason reason)
			{
				if (reason == CacheItemRemovedReason.Expired)
				{
					if (this.Enabled == true)
					{
						this.StartRunning(callback, context);
					}

					if (this.FirstTime == true)
					{
						this.FirstTime = false;
						this.OnStart(EventArgs.Empty);
					}

					this.OnTick(EventArgs.Empty);

					if (this.Enabled == false)
					{
						this.OnStop(EventArgs.Empty);
					}
				}
			};

			this.StartRunning(callback, context);
		}

		protected void StartRunning(CacheItemRemovedCallback callback, HttpContext context)
		{
			context.Cache.Add(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DateTime.Now + this.Interval, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, callback);
		}
		#endregion

		#region Protected virtual methods
		protected virtual void OnStart(EventArgs e)
		{
			EventHandler handler = this.Start;

			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}

		protected virtual void OnStop(EventArgs e)
		{
			EventHandler handler = this.Stop;

			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}

		protected virtual void OnTick(EventArgs e)
		{
			EventHandler handler = this.Tick;

			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}
		#endregion

		#region IHttpModule Members

		public void Dispose()
		{
			this.Enabled = false;	
		}

		public void Init(HttpApplication context)
		{
			this.StartScheduler();
		}

		#endregion
	}


Expõe duas propriedades:

  • Enabled: se o agendador de tarefas está activo
  • Interval: o intervalo de disparo

Para a instalação, apenas é preciso referenciá-lo no web.config:

    
    
      
    
    
    
      
        
      
    

Existem duas formas pelas quais o podemos usar: manualmente adicionando um evento, talvez no Application_Start, ou criando métodos especiais, usem um ou o outro, não os dois!

protected void Application_Start(Object sender, EventArgs e)
{
	//Nota: nao e preciso fazer isso se criarem os outros metodos!	
	SchedulerModule schedulerModule = HttpContext.Current.ApplicationInstance.Modules.OfType<SchedulerModule>().Single();

	//Definir o intervalo de disparo
	schedulerModule.Interval = TimeSpan.FromMinutes(5);
	
	schedulerModule.Start += this.Scheduler_Start;
	schedulerModule.Stop += this.Scheduler_Stop;
	schedulerModule.Tick += this.Scheduler_Tick;
}

protected void Scheduler_Start(Object sender, EventArgs e)
{
}

protected void Scheduler_Stop(Object sender, EventArgs e)
{
}

protected void Scheduler_Tick(Object sender, EventArgs e)
{
}

Bookmark and Share


Posted 6-7-2010 14:33 por Ricardo Peres
Filed under: ,

Add a Comment

(requerido)  
(opcional)
(requerido)  
Remember Me?
If you can't read this number refresh your screen
Enter the numbers above:  
Powered by Community Server (Commercial Edition), by Telligent Systems