Before ASP.NET Core, I used to implement timers like that :
public class Class1
{
Timer tm = null;
public Class1()
{
this.tm.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
this.tm.AutoReset = true;
this.tm = new Timer(60000);
}
protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
this.tm.Stop();
try
{
// My business logic here
}
catch (Exception)
{
throw;
}
finally
{
this.tm.Start();
}
}
}
I have the same need on a .NETCoreApp1.1 console application and System.Timers doesn't exist anymore with ASP.NET Core. I also try to use System.Threading.Timer but the project doesn't build anymore.
How can I implement a Timer with .NETCoreApp1.1 ? Is there an equivalent of System.Timers ?
Timer Control in ASP.NET framework helps in providing a trigger to postback every ‘n’ number of milliseconds.by using Timer control functionality we can build many more applications where time constraint matters to an application including bank application such as token generation for security purpose. Timer Control makes developers’ life easy.
Examples to Implement Timer in C#. Below are the example of C# code to demonstrate the working of timers: Example #1. Code: using System ; using System.Timers ; class Timer_Example {public static void Main() {Timer newTimer = new Timer() ; newTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent ) ; newTimer.Interval = 2000 ; newTimer.Start() ;
app.myTimer = timer ('Period',2,... 'ExecutionMode', 'fixedSpacing', ... Note, if you need to wire your timer callback to a function inside your app, the TimerFcn syntax would be a little different. You can reference this post for a few options for that:
When you create a System.Threading.Timer object, you specify a TimerCallback delegate that defines the callback method, an optional state object that is passed to the callback, the amount of time to delay before the first invocation of the callback, and the time interval between callback invocations.
Ok, so to implement a timer with .NETCoreApp1.0 or .NETCoreApp1.1, you have to use System.Threading.Timer. It works almost like System.Timers, you have all the documentation here : https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
If your project doesn't build anymore after adding the System.Threading.Timer package, it's because you have to add a dependency to the platform version of Microsoft.NETCore.App to your netcoreapp framework :
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"System.Threading.Timer": "4.3.0"
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": "dnxcore50"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With