Skip to content

Instantly share code, notes, and snippets.

@SarahBourgeois
Last active November 15, 2022 08:10
Show Gist options
  • Save SarahBourgeois/680b6e05947de3ed4370ff7dce5828fb to your computer and use it in GitHub Desktop.
Save SarahBourgeois/680b6e05947de3ed4370ff7dce5828fb to your computer and use it in GitHub Desktop.
C# Execute specified function every X minutes or X time you want in a thread
using System;
using System.Timers;
namespace CallFunction
{
public class Program
{
public Program()
{
// timer to call MyMethod() every minutes
System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(MyMethodCall);
timer.Start();
}
public static void MyMethod(object sender, ElapsedEventArgs e)
{
Console.WriteLine("I will be call every minutes !!!");
}
}
}
@AldeRoberge
Copy link

There's a little typo. It should be "MyMethod" instead of "MyMethodCall".

@xanat0s
Copy link

xanat0s commented Aug 26, 2022

Aside from the typo, new System.Timers.ElapsedEventHandler() is redundant.

timer.Elapsed += MyMethod is sufficient and more concise.

@evanwheelrr
Copy link

There's a little typo. It should be "MyMethod" instead of "MyMethodCall".

Yes!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment