0

I have a requirement where the Asp.Net Core Application(Deployed to IIS) needs to send data external domain("http://example.com/api/statistics") at a given time everyday(only once a day; say 6PM localTime where application is running). I am hesitant to place code any place(like in Startup.cs or Program.cs) that might create problems later. Something like the following : Your insights highly appreciated. Thank you.

        Task.Run(() =>
        {
            while (true)
            {

                using (var client = new HttpClient())
                {

                    var response =  client.PostAsync("http://example.com/api/statistics",
                        new StringContent(JsonConvert.SerializeObject("data"), 
                        Encoding.UTF8, "application/json"));
                }
            }

        });
Raj
  • 343
  • 2
  • 6
  • 16
  • 1
    Create a regular app and use the Windows task scheduler to do this for you. – CodingYoshi Feb 02 '18 at 03:23
  • Possible duplicate of [ASP.NET Core MVC scheduled task](https://stackoverflow.com/questions/40050753/asp-net-core-mvc-scheduled-task) – Keith Nicholas Feb 02 '18 at 03:49
  • not sure if it absolutely has to run on the IIS Application, but if it does I'd be inclined to build a scheduler based on [QueueBackgroundWorkItem](https://blogs.msdn.microsoft.com/webdev/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-background-processes-in-asp-net/). But you can't guarantee it will run, and you'd have to build in rules to determine what happens if the app pool is being recycled when the scheduled time is hit, for example. Personally I like @Keith's idea. – pcdev Feb 02 '18 at 04:37
  • Use something like Hangfire, or you can use `IHostedService` in ASP.NET Core 2.0 to achieve something similar (https://blog.maartenballiauw.be/post/2017/08/01/building-a-scheduled-cache-updater-in-aspnet-core-2.html) – Chris Pratt Feb 02 '18 at 14:36

1 Answers1

1

There's a number of ways to approach this, however the way I think works well is make a controller with an action which will do the post. That way anything can trigger the posting of statistics ( you will want an authorization token of some sort so only things that are meant to trigger the action can do it )

so something like mysite/statistics/post?url=<destination url>&...any other options

then you can use a scheduled task, or manually trigger it, or trigger it via a webhook, or any other mechanisim. You can even still use a Task that waits for a particular time then calls your hook.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • Thanks Keith. The post has to happen internally . Let's say on startup a if statements checks for it time is 6 pm . , if i create a controller what will call it? – Raj Feb 02 '18 at 03:45
  • actually, there's a SO question covering this... https://stackoverflow.com/questions/40050753/asp-net-core-mvc-scheduled-task – Keith Nicholas Feb 02 '18 at 03:49