在一天中的特定时间调用方法

时间:2016-08-29 08:54:39

标签: c# asp.net multithreading time task

我想在一天中的特定时间调用方法,而无需向任何页面请求:

更新:我是使用以下课程完成的,没有任务时间表或其他内容

像Windows计划

之类的东西

我在课堂上做过:

public class Class1 {

    private const string DummyCacheItemKey = "GagaGuguGigi";

    protected void Application_Start(Object sender, EventArgs e) {
        var Result = RegisterCacheEntry();
        if (!Result) {
            Debug.WriteLine("The DummyCacheItem is Alive!");
        }
    }

    public bool RegisterCacheEntry() {
        if (null != HttpContext.Current.Cache[DummyCacheItemKey])
            return false;
        try {
            HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.MaxValue, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheItemRemovedCallback));

        }catch( Exception Ex) {
            Debug.WriteLine("Exeption Error: " + Ex);
        }
        return true;
    }

    public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason) {
        Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString() + " Removed!");

        try {
            HitPage();
        }catch(Exception Ex) {
            Debug.WriteLine("HitPage Was unsuccessful: " + Ex);
        }

        // Do the service works


        DoWork();
        //SendMail();

    }

    private const string DummyPageUrl = "http://localhost:53509/Page.cshtml";

    private void HitPage() {
        WebClient client = new WebClient();
        client.DownloadData(DummyPageUrl);
    }


    protected void Application_BeginRequest(Object sender, EventArgs e) {
        // If the dummy page is hit, then it means we want to add another item

        // in cache

        if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl) {
            // Add the item in cache and when succesful, do the work.

            RegisterCacheEntry();
        }
    }

    private void DoWork() {
        Debug.WriteLine("Begin DoWork...");
        Debug.WriteLine("Running as: " +
              WindowsIdentity.GetCurrent().Name);

        DoSomeFileWritingStuff();

        Debug.WriteLine("End DoWork...");
    }


    private void DoSomeFileWritingStuff() {
        Debug.WriteLine("Writing to file...");

        try {
            using (StreamWriter writer =
             new StreamWriter(@"c:\temp\Cachecallback.txt", true)) {
                writer.WriteLine("Cache Callback: {0}", DateTime.Now);
                writer.Close();
            }
        } catch (Exception x) {
            Debug.WriteLine("Error: " + x);
        }

        Debug.WriteLine("File write successful");
    }
}

以下是对why i did this?

的解释

有更简单的方法吗?

3 个答案:

答案 0 :(得分:0)

使用"任务计划程序"在特定时间运行程序。

通过输入"任务计划程序"找到它在开始菜单中。

答案 1 :(得分:0)

这取决于你在这里尝试做什么。如果您只需要在给定时间执行某些代码,请使用Windows scheduler。

如果由于某种原因需要从您的Web应用程序执行此操作,您可以使用http://www.quartz-scheduler.net/并在Web应用程序中托管它。只需确保您的应用程序池设置为始终运行,以便任务计划程序保持活动状态。

答案 2 :(得分:0)

24小时计时器运行正常

var DailyTime = "16:59:00";
            var timeParts = DailyTime.Split(new char[1] { ':' });

            var dateNow = DateTime.Now;
            var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
                       int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
            TimeSpan ts;
            if (date > dateNow)
                ts = date - dateNow;
            else
            {
                date = date.AddDays(1);
                ts = date - dateNow;
            }

            //waits certan time and run the code
            Task.Delay(ts).ContinueWith((x) => OnTimer());