How implement a timer with .NETCoreApp1.1

AdrienTorris picture AdrienTorris · Jan 16, 2017 · Viewed 10.3k times · Source

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 ?

Answer

AdrienTorris picture AdrienTorris · Jan 16, 2017

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"
    }
  }
}