ASP.NET / C#: Run command at specific interval

喜你入骨 提交于 2020-01-06 19:05:29

问题


I have an auction site coded using SinglarR, and MVC5.I have a credit card token stored in my database for every single bidder. At the end of the auction, the winning bidder's credit card needs to be charged.

What would be the most efficient way to accomplish this? I thought about using a filter, however, the code would only be ran the next time a visitor arrives, which might be a long period of time on some days


回答1:


Sounds like you need a scheduled task. It can be done with HttpModule. Implement something like:

public class CheckAuctionsScheduleModule : IHttpModule
{
    static Timer timer;
    long interval = 60000; //60 secs
    static object synclock = new object();
    public void Init(HttpApplication app)
    {
        if(timer==null) timer = new Timer(new TimerCallback(CheckAuctions), null, 0, interval);
    }

    private void CheckAuctions(object obj)
    {
        lock (synclock)
        {
           //implement here your logic
           //check completed auctions
           //send notifications to bidder etc.  

        }
    }
    public void Dispose()
    { 
    //implement if needed
    }
}

In your web.config:

<system.webServer>
  <modules>
    <add name="CheckAuctionsSchedule" type="MyMvcApp.Modules.CheckAuctionsScheduleModule"/>
  </modules>
</system.webServer>

Note: Module works as long as MVC application running. There are other solutions for scheduled tasks(as microsoft recommends win services). This can be useful.



来源:https://stackoverflow.com/questions/29787600/asp-net-c-run-command-at-specific-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!