How to schedule a C# code execution

前端 未结 2 1452
陌清茗
陌清茗 2020-12-07 03:18

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

相关标签:
2条回答
  • 2020-12-07 03:57

    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.

    0 讨论(0)
  • 2020-12-07 04:09

    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));
    }
    
    0 讨论(0)
提交回复
热议问题