如何安排 C# 代码执行 [英] How to schedule a C# code execution

查看:35
本文介绍了如何安排 C# 代码执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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.

如果我制作一个网络服务,我应该如何在每天的特定时间调用它?

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

例如,我想每天晚上 7 点运行方法.

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# 代码执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆