Skip to content

Instantly share code, notes, and snippets.

@battleguard
Created December 15, 2015 06:56
Show Gist options
  • Select an option

  • Save battleguard/3ae2822ef8978fd8e1f4 to your computer and use it in GitHub Desktop.

Select an option

Save battleguard/3ae2822ef8978fd8e1f4 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
public static void Main()
{
var action = new Action( MethodA).Timed(TimeSpan.FromSeconds(7));
action.Invoke(); // called
Thread.Sleep( 5000 );
action.Invoke(); // not called
Thread.Sleep( 5000 );
action.Invoke(); // called
}
public static void MethodA()
{
Console.WriteLine( "Method A Invoked" );
}
}
public static class ActionExtension
{
public static Action Timed( this Action action, TimeSpan interval )
{
DateTime lastCalled = DateTime.MinValue;
return () =>
{
if ( DateTime.Now - lastCalled < interval )
return;
action.Invoke();
lastCalled = DateTime.Now;
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment