问题描述
我使用ASP.Net和C#。我想在一个特定的时间同步的东西。我做了一个方法,这样做的,它的工作。但我的问题是,如何在特定的时间每天调用此方法。
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服务并不是一个很好的解决方案。
Windows service is not a good solution.
如果我做一个Web服务,我应该怎么称呼它在每天特定的时间?
If I make a web service, how should I call it at a particular time on a daily basis?
例如,我要天天在方法下午7时00运行。
For example, I want to run method everyday at 07.00 PM.
推荐答案
在启动时,添加项目到HttpRuntime.Cache具有固定到期。
当缓存项到期,做你的工作,如WebRequest的或你有什么。
重新添加的项目有固定到期缓存。
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));
}
这篇关于如何安排一个C#code执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!