How to schedule a C# code execution

本秂侑毒 提交于 2019-12-28 07:01:20

问题


I am using ASP.Net and C#. I want to synchronise something on a particular time. I made a method for doing this and it's working. But my problem is how to call this method daily at a particular time.

Client doesn't trust any third party tool, so can't use it.

Windows service is not a good solution.

If I make a web service, how should I call it at a particular time on a daily basis?

For example, I want to run method everyday at 07.00 PM.


回答1:


At startup, add an item to the HttpRuntime.Cache with a fixed expiration. When cache item expires, do your work, such as WebRequest or what have you. Re-add the item to the cache with a fixed expiration.

private static CacheItemRemovedCallback OnCacheRemove = null;

protected void Application_Start(object sender, EventArgs e)
{
    AddTask("DoStuff", 60);
}

private void AddTask(string name, int seconds)
{
    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
    HttpRuntime.Cache.Insert(name, seconds, null,
        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
}

public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // do stuff here if it matches our taskname, like WebRequest
    // re-add our task so it recurs
    AddTask(k, Convert.ToInt32(v));
}



回答2:


You can use windows scheduled task to run the application (exe) or create windows service and use timer. Take a look at Quartz.NET it also can used.



来源:https://stackoverflow.com/questions/10794534/how-to-schedule-a-c-sharp-code-execution

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